ruby-on-rails - 在 Rails 4.2 中使用 Arel 的 WHERE 子句中的 OR 运算符

标签 ruby-on-rails arel

以下代码构造了一个有效的 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/

相关文章:

ruby-on-rails - 为什么 Rails 迁移在应用程序中而不是在数据库中定义外键?

ruby-on-rails - Rails生成抛出Minitest错误?

mysql - Rails Controller 接收所有参数,但无法正确创建数据库记录

ruby-on-rails - 在具有与同一个 STI 表的 has_many 关系的查询中重用范围

sql - 在加入时用 Arel 连接变量和字符串

ruby-on-rails - 接收电子邮件 POP3 并保存在数据库中

ruby-on-rails - 如何设置 url 帮助器方法参数的默认值?

ruby-on-rails - ActiveRecord、方法链和请求执行

ruby-on-rails - Rails 使用哈希数组查找记录

ruby - 使用 ActiveRecord 插入时如何使用 SQL 函数?