Reputation: 169
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
Reputation: 44581
You can query only by parameters that are present:
args = { name: @name, salary: @salary.presence }
Employee.where(args.compact)
Upvotes: 6
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
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