2017-08-28 26 views
0

我有一個很多參數的過濾器,我會知道寫在我的控制器中的最佳方式,我的條件工作,但單獨我想知道寫它的好方法,並使其與所有我使用參數創造條件,9999像在控制器中的過濾器參數

我控制器 「params.present & & params.present等等......?」:

if params[:room_type].present? 
     @biens = Bien.where(room_type: params[:room_type]) 
    elsif params[:nb_piece].present? 
     @biens = Bien.where(nb_piece: params[:nb_piece]) 
    elsif params[:nb_piece].present? && params[:room_type].present? 
     @biens = Bien.where(nb_piece: params[:nb_piece], room_type: params[:room_type]) 
    elsif params[:location].present? 
     @biens = Bien.near(params[:location], 1, units: :km) 
    elsif params[:nb_piece].present? && params[:room_type].present? 
     @biens = Bien.where(nb_piece: params[:nb_piece]) && Bien.where(room_type: params[:room_type]) 
    elsif params[:start_date].present? && params[:end_date].present? 
     @biens = Bien.where(compromis_date: Date.parse(params[:start_date])..Date.parse(params[:end_date])) 
    elsif params[:start_price].present? && params[:end_price].present? 
     @biens = Bien.where(prix: params[:start_price]..params[:end_price]) 
    elsif params[:negociateur].present? 
     @biens = Bien.where(negociateur: params[:negociateur]) 
    else 
     @biens = Bien.all 
    end 
+0

檢查Filterrific寶石http://filterrific.clearcove.ca/pages/active_record_model_api.html或者申請從賈斯汀·維斯簡單的解決方案:https://www.justinweiss.com/articles/search-and-filter-軌的模型,沒有腹脹,您的控制器/ –

回答

0

我相信下面的解決方案,你會工作。我沒有測試過,但類似的東西應該可以工作。請嘗試一下,如果您對此有任何疑問,請在評論中告訴我。

params.each do|key, value| 
    next if params[key.to_sym].blank? 
    @biens = Bien.where(key.to_sym => value) 
    break 
end 
if @biens.blank? 
    @biens = Bien.all 
end