nullnullnull
nullnullnull

Reputation: 8189

Build an ActiveRecord query with multiple conditional clauses

With ActiveRecord, you can build upon a query like so:

query = MyModel.where(value_one: true)
if (condition)
  query.where(value_two: true)
else
  query
end

However, I'm running into problems when there are multiple conditionals:

query = MyModel.where(value_one: true)
query.where(value_two: true) if condition_two
query.where(value_three: true) if condition_three
query

In this case, it'll only check that value_one is true. Interestingly, if I:

query = MyModel.where(value_one: true)
query.where(value_two: true)
query.where(value_three: true)

Then it'll check if value_one and value_three are true, but not value_two. Anyone understand why this is and how to get the query clauses to properly build upon each other?

Upvotes: 0

Views: 809

Answers (1)

eirikir
eirikir

Reputation: 3842

When you chain queries or scopes, ActiveRecord returns another Relation object with the additional conditions; it does not modify the original object. To modify a relation, you need to chain the query and assign the result, e.g.:

query = MyModel.where(value_one: true)
query = query.where(value_two: true) if condition_two
query = query.where(value_three: true) if condition_three
query

Note that the query is not actually executed until you attempt to extract the data, whether through to_s, each, etc.

Upvotes: 3

Related Questions