Reputation: 6981
Is this the best way to write an index method that can accommodate multiple param queries?
if params.key?(:user_id)
Post.where(user_id: params[:user_id])
elsif params.key?(:status)
Post.where(status: params[:status])
elsif params.key?(:user_id) && params.key?(:status)
Post.where(user_id: params[:user_id], status: params[:status])
else
Post.all
end
My method doesn't seem to catch the params when there are two.
Upvotes: 0
Views: 137
Reputation: 13477
I would use ActionController::Parameters#slice
:
post_parmas = params.slice(:user_id, :status)
post_params.empty? ? Post.all : Post.where(post_params)
Your code problem: if you have :user_id
or :status
keys, you are skipping all other logic, including both params presence checking. Checking both params (condition #3) should be first.
Upvotes: 6
Reputation: 3798
This will work for you
if params.key?(:user_id) && params.key?(:status)
Post.where(user_id: params[:user_id], status: params[:status])
elsif params.key?(:user_id)
Post.where(user_id: params[:user_id])
elsif params.key?(:status)
Post.where(status: params[:status])
else
Post.all
end
If you have multiple conditions need to be added in query based on parameters , you can use below approach. Please take care SQL injection.
condition = ""
if(params[:user_id].blank? and params[:user_id].blank?)
Post.all
else
condition += "user_id=#{params[:user_id]}" if params.key?(:user_id)
condition += " AND status=#{params[:status]}" if params.key?(:status)
Post.where("#{condition}")
end
Upvotes: 0