2011-01-22 76 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') 

當父類別/位置標題更改時,留給讀者作爲練習更新帖子。