繁体   English   中英

Rails 5通过OR加入activerecord范围

[英]Rails 5 joining activerecord scopes with OR

我想用OR加入2个作用域。

scope :unassigned, -> {
  where(dongle_id: nil)
}

scope :driverless, -> {
  left_outer_joins(:customer).where(customers: { id: nil })
}

现在我正在这样做,因为我无法弄清楚:

scope :inactive, -> {
  left_outer_joins(:customer).where(
    'customers.vehicle_id IS ? OR vehicles.dongle_id IS ?', nil, nil
  )
}

范围表示数据库查询的范围缩小,例如where(color::red).select('shirts。*')。includes(:washing_instructions)( https://api.rubyonrails.org/classes/ActiveRecord/Scoping /Named/ClassMethods.html#method-i-scope

无法使用OR条件连接作用域。 范围通过某些过滤器缩小了结果集。 将范围链接在一起等效于同时使用范围过滤器,即SQL的AND条件。

对于您需要将两个合并范围合并在一起的情况,可以合并其结果集:

Vehicle.unassigned.to_a | Vehicle.driverless.to_a

但是最好像您已经写过的那样编写另一个作用域。

这是您要找的东西吗?

scope :inactive, -> { unassigned.or(driverless) }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM