简体   繁体   中英

Dynamic conditions query in RoR

I'm trying to make query in RoR, but my conditions are coming from params and changing dynamically.

I've tried this:

@userlist = User.find(:all, conditions:{(name:params[:name] if params[:name] != nil), (lastname:params[:lastname] if params[:lastname] != nil)})

It's just my imagination, but shows what I mean.

thanx

If you're on Rails 3:

@userlist = User.scoped
@userlist = @userlist.where(name: params[:name]) if params[:name].present?
@userlist = @userlist.where(lastname: params[:lastname]) if params[:lastname].present?

etc..

you could do something like:

BlahController < ActiveController::Base
  before_filter :find_params, :only => :index

  def index
    @user_list = User.where(@filtered_params).all
  end

  def find_params
    @filtered_params = params[:name].present? ? "'name = ?', #{params[:name]}" : "'last_name = ?', #{params[:last_name]}"
  end

end

So I assume you only have two conditions, a params[:name] or a params[:last_name] . If there are more, simply change the ternary to a if elsif statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM