2013-01-05 48 views
6

我想在我的rails應用程序(仍然是noob)中建立一個搜索結果頁面,我無法弄清楚如何建立一個查詢的軌道方式。如何有條件地在Rails中構建ActiveRecord查詢?

例如,如果沒有參數存在,我想返回所有結果。如果用戶在搜索表單中傳遞1個n個可選參數,我想將它們添加到查詢中。

接下來,如果他們有一個指定的「price desc」或「year_built desc」或甚至兩者的組合。

最後用will_paginate來分隔結果

# default to all listings 
@listings = Mls.all 

@listings.where("listing_price > ?", params[:listing_price]) unless params[:listing_price].blank? 
# ... bunch of other search options ... 
@listings.where("property_type = ?", params[:property_type]) unless params[:property_type].blank? 

# order 
@listings.order("some order by param") if some sort param 
@listings.order("some order by param") if some other sort param 

# paginate results 
@listings.paginate(:page => params[:page]) 

是否有這樣做的「導軌」的方式?

+1

你應該代碼的循環和範圍 – apneadiving

+0

我不知道這是否是真的是這個問題的答案,但[has_scope](https://github.com/plataformatec/has_scope)很好地解決了我的問題。 –

回答

21

你見過(修訂)Railscasts先進的搜索插曲?這裏是鏈接:http://railscasts.com/episodes/111-advanced-search-form-revised

基本的想法是創建一個Search的資源,將處理過的形式,並在對有關​​模型中的後臺搜索發送搜索PARAMS(你的情況Mls

通過這種方式,而不是在控制器檢查某些參數的存在(如params[:listing_price]),你可以在你的搜索模型(模型/ search.rb)辦理條件:

def find_listings 
    listings = Mls.order(:name) 
    listings = listings.where("listing_price > ?", listing_price) if listing_price.present? 
    # ... more condition checking 
    listings 
end 
+0

我喜歡那樣,thx – Batman