vishwas tej
vishwas tej

Reputation: 169

Apply where condition if it exists in rails

is there a way in rails activerecord to apply the where condition based on a condition ?

For example: Say I want to apply the filter if it is present in the input parameters. Assume @name is a mandatory field and @salary is an optional field.

@name = "test_name"
@salary = 2000

I want to do something like below:

Employee.where(name: @name)
        .where(salary: @salary) if @salary.present?

I know to make it in multiple db calls, but I'm looking for an option to make this happen in a single db call.

Upvotes: 3

Views: 3284

Answers (3)

potashin
potashin

Reputation: 44581

You can query only by parameters that are present:

args = { name: @name, salary: @salary.presence }
Employee.where(args.compact)

Upvotes: 6

spickermann
spickermann

Reputation: 106782

You can just add all possible arguments into one hash and remove the ones that are nil with Hash#compact:

Employee.where({ name: @name, salary: @salary }.compact)

Upvotes: 3

Stefan
Stefan

Reputation: 114138

You can assign the result of the 1st where to a variable and invoke the 2nd where conditionally:

@employees = Employee.where(name: @name)
@employees = @employees.where(salary: @salary) if @salary.present?

Upvotes: 6

Related Questions