2013-01-05 4 views
6

私は自分のレールアプリ(まだnoob)に検索結果ページを構築しようとしていますが、私はレールのようにクエリを構築する方法を理解できません。どのように条件付きでActiveRecordクエリをRailsで構築できますか?

たとえば、パラメータが存在しない場合、すべての結果を返したいとします。ユーザーが検索フォームに1〜n個のオプションのパラメーターを渡した場合、それらをクエリに追加したいと思います。

次に、「price desc」または「year_built desc」、またはその両方の組み合わせを指定した並べ替えがある場合。最後に

結果

# 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]) 

を分離するためにwill_paginateを使用してこれを行うには「レール」方法はありますか?

+1

あなたはループやスコープをコーディングする必要があり – apneadiving

+0

これがもしかしたら私は分かりません本当に質問への答えだが、[has_scope](https://github.com/plataformatec/has_scope)は問題をきれいに解決した。 –

答えて

21

を見たことがありますか?ここにリンクがある:http://railscasts.com/episodes/111-advanced-search-form-revised

基本的な考え方は、(Mlsあなたのケースで)問題のモデル上のフォームを通じて、バックグラウンド検索で送られてきた検索のparamsを処理するSearchリソースを作成することです

こうすることで、代わりにあなたの検索モデル(モデル/ search.rb)の状況を扱うことができる特定のパラメータ(例えばparams[:listing_price])の存在のためのコントローラでチェック:

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

関連する問題