I know there are 3 main notations for supplying arguments to the where
ActiveRecord method:
- Pure String
- Array
- Hash
Specifying and
for the where
method is straight forward:
# Pure String notation
Person.where("name = 'Neil' AND age = 27")
# Array notation
Person.where(["name = ? AND age = ?", 'Neil', 27])
# Hash notation
Person.where({name: "Neil", age: 27})
Specifying or
for this same where
method is stumping me for the hash syntax. Is it possible?
# Pure String notation
Person.where("name = 'Neil' OR age = 27")
# Array notation
Person.where(["name = ? OR age = ?", 'Neil', 27])
# Hash notation DOESN'T WORK
Person.where({name: "Neil" OR age: 27})
As says potashin, you can use another third-party plugins that implement this feature. I have a long time using Squeel and works pretty well for this and much more features like complex subqueries or joins.
That query using squeel:
There are 5 options that could be considered as implementations of «Hash notation» (the last two are kinda hash-ish):
With Ruby on Rails 5 you are able to do the following chaining using
ActiveRecord::Relation#or
method:Use
where_values
together withreduce
. Theunscoped
method is necessary only for Rails 4.1+ to ensuredefault_scope
is not included in thewhere_values
. Otherwise predicates from bothdefault_scope
andwhere
would be chained with theor
operator:Install third-party plugins that implement these or similar features, for example:
Where Or (backport of the Ruby on Rails 5
.or
feature mentioned above)Squeel
RailsOr
ActiverecordAnyOf
SmartTuple
Use Arel:
Use prepared statements with named parameters: