2011-01-22 65 views
2

我有一些帖子属于位置和类别,有点像craigslist帖子。Rails:范围顺序问题

我想按最近发布的顺序进行排序,如果用户指定,也按位置和类别进行筛选。

有人可以举一个例子/提示如何做到这一点?

回答

4

在Rails 3中,您可以一起更改命令,wheres等。 ASCICast 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 
+1

如何指定location_id? – SuperString 2011-01-23 06:56:59

0

您可以缓存将用于排序类别和位置的字段到帖子中。

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') 

当父类别/位置标题更改时,留给读者作为练习更新帖子。