开发者

Rails: scope order question

I have some posts that belongs to location and category, sort of like craigslist post.

I want to order by most recently posted and also filter by location and category if those are specified by the user.

Can someon开发者_开发问答e give an example/hints on how to do this?


In Rails 3 you can change together orders, wheres and more. ASCICasts on activerecord queries in Rails3

query = Post.order("published_at desc")
query = query.where("location_id = ?", params[:location_id]) unless params[:location_id].blank?
query = query.where("category_id = ?", params[:category_id]) unless params[:category_id].blank?
@posts = query.all


You can cache the field you would use to sort be category and location into the post.

before_save: cache_sortables

def cache_sortables
  self.category_title = self.category.title if self.category?
  self.location_title = self.location.title if self.location?
end

Post.find(:all, :order => 'location_title, category_title, created_at')

It is left as an exercise to the reader to update the posts when the parent category/location title changes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜