下面的代码在Rails 4.1中构造了一个where带有OR运算符的有效子句
MyModel.where(
MyModel.where(attribute1: 1, attribute2: 2).where_values.reduce(:or)
)
Run Code Online (Sandbox Code Playgroud)
这大致相当于SQL
select * from my_models where (attribute1 = 1 OR attribute2 = 2)
Run Code Online (Sandbox Code Playgroud)
在Rails 4.2中,相同的代码生成一个SQL查询,其缺少值的绑定参数
select * from my_models where attribute1 = OR attribute2 =
Run Code Online (Sandbox Code Playgroud)
...并且由于缺少绑定值的值而生成错误.
Rails 4.2中用OR运算符生成有效查询的等效代码是什么?
编辑:
该解决方案需要使用Arel::Nodes::Node派生对象,以便它本身可以通过AND和OR分组与其他条件组合.
rel = MyModel.where(attribute1: 1, attribute2: 2)
conditions = [rel.where_values.reduce(:or).to_sql, *rel.bind_values.map(&:last)]
MyModel.where(conditions)
Run Code Online (Sandbox Code Playgroud)
该conditionsVAR必须的衍生物Arel::Nodes::Node.上述解决方案适用于简单查询,但对于更复杂的查询,conditions必须将Arel节点传递给最终查询方法.