简体   繁体   中英

Model.where() with multiple params with check if they are present in rails

I am new to Rails. I started working on a POC.

My controller code is below:

  @xyz = if params[:id].present?
           if params[:mobile_number].present?
             Seeker.where("id = ? and mobile_number = ?" , params[:id], params[:mobile_number])                    
           else                    
             Seeker.where("id = ?", params[:id])
           end
         elsif params[:seekerid].present?
           Seeker.where("mobile_number = ?" , params[:mobile_number])
         else
           Seeker.where(nil);
         end

But I don't think it's a good approach. Consider if I have many parameter then putting present? condition then forming query would become complex. Or can I form a query separately then place it into where condition as instance variable.

What is the best approach?

You could add where statements incrementally when each parameter is present:

@xyz = Seeker.scoped
@xyz = @xyz.where(id: params[:id]) if params[:id].present?
@xyz = @zyx.where(mobile_number: params[:mobile_number]) if params[:mobile_number].present?

A cleaner approach could be to move that logic to some scope or class method in the Seeker model maybe.

Hi I am new to Rails

If you are using searching for small project, small database, you can use Ruby's scope , and take a look at arieljuod's answer. But if you want to make your searching feature is faster, deeper, ... you can find some gems:

And there are many other amazing ways with Ruby on Rails.

Happy coding!!!

If you want to find record based on each parameter are coming and have value that best way to use this is

params = {id: nil, mobile_number: "98XXXXXX12" }
Seeker.where(params.compact)

compact will remove nil value from params and directly find with Existing parameter.

NOTE: It will remove only nil value not " " blank String

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