以下代码构造了一个有效的 where
带有 OR
的子句Rails 4.1 中的运算符
MyModel.where(
MyModel.where(attribute1: 1, attribute2: 2).where_values.reduce(:or)
)
大致相当于SQL
select * from my_models where (attribute1 = 1 OR attribute2 = 2)
在 Rails 4.2 中,相同的代码会生成一个 SQL 查询,但它的绑定(bind)参数缺少值
select * from my_models where attribute1 = OR attribute2 =
...并由于绑定(bind)值的缺失值而生成错误。
中的等效代码是什么? 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)
conditions
var 必须是 Arel::Nodes::Node
的导数.上述解决方案适用于简单查询,但对于更复杂的查询,conditions
必须是要传递给最终查询方法的 Arel 节点。
最佳答案
我正在使用以下内容,直到 rails 5 出来(在 rails 5 AR 支持 .or
):
ActiveRecord::QueryMethods::WhereChain.class_eval do
def or(*scopes)
scopes_where_values = []
scopes_bind_values = []
scopes.each do |scope|
case scope
when ActiveRecord::Relation
scopes_where_values += scope.where_values
scopes_bind_values += scope.bind_values
when Hash
temp_scope = @scope.model.where(scope)
scopes_where_values += temp_scope.where_values
scopes_bind_values += temp_scope.bind_values
end
end
scopes_where_values = scopes_where_values.inject(:or)
@scope.where_values += [scopes_where_values]
@scope.bind_values += scopes_bind_values
@scope
end
end
有了上面你可以做:
MyModel.where.or(attribute1: 1, attribute2: 2)
# or
MyModel.where.or(MyModel.where(some conditions), MyModel.where(some other conditions))
关于ruby-on-rails - 在 Rails 4.2 中使用 Arel 的 WHERE 子句中的 OR 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27627390/