The following code constructed a valid where
clause with an OR
operator in Rails 4.1
MyModel.where(
MyModel.where(attribute1: 1, attribute2: 2).where_values.reduce(:or)
)
Which is roughly equivalent to the SQL
select * from my_models where (attribute1 = 1 OR attribute2 = 2)
In Rails 4.2, the same code generates an SQL query with missing values for it's bind parameters
select * from my_models where attribute1 = OR attribute2 =
... and generates an error due to the missing values for the bound values.
What is the equivalent code in Rails 4.2 to generate a valid query with an OR operator?
Edit:
The solution requires an Arel::Nodes::Node
derived object to be used so that it can itself be combined with other conditions via AND and OR groupings.
rel = MyModel.where(attribute1: 1, attribute2: 2)
conditions = [rel.where_values.reduce(:or).to_sql, *rel.bind_values.map(&:last)]
MyModel.where(conditions)
The conditions
var must be a derivative of Arel::Nodes::Node
. The above solution works for simple queries, but for more complicated queries, conditions
must be an Arel Node to be passed to a final query method.
Model.where(conditions).where_values.reduce(:or).to_sql
return? – Faraday"(attribute1 = ? OR attribute2 = ?)"
– Malignant