过滤控制器中的参数

时间:2017-08-28 13:36:39

标签: ruby-on-rails

我有一个带有很多参数的过滤器,我知道在我的控制器中编写它的最好方法,我的条件有效但我个人想知道编写它的好方法并使它与我的所有参数一起使用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

1 个答案:

答案 0 :(得分: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