【发布时间】:2011-01-22 18:53:46
【问题描述】:
我有一些属于位置和类别的帖子,有点像 craigslist 帖子。
我想按最近发布的排序,如果用户指定,还按位置和类别进行过滤。
有人可以举例说明如何做到这一点吗?
【问题讨论】:
标签: sql ruby-on-rails database ruby-on-rails-3 sorting
我有一些属于位置和类别的帖子,有点像 craigslist 帖子。
我想按最近发布的排序,如果用户指定,还按位置和类别进行过滤。
有人可以举例说明如何做到这一点吗?
【问题讨论】:
标签: sql ruby-on-rails database ruby-on-rails-3 sorting
在 Rails 3 中,您可以一起更改订单、位置等。 ASCII 广播 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
【讨论】:
您可以将用于排序的字段缓存到帖子中。
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')
当父类别/位置标题更改时更新帖子作为练习留给读者。
【讨论】: