我想在我的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])
是否有這樣做的「導軌」的方式?
你應該代碼的循環和範圍 – apneadiving
我不知道這是否是真的是這個問題的答案,但[has_scope](https://github.com/plataformatec/has_scope)很好地解決了我的問題。 –