简体   繁体   English

Rails 5通过OR加入activerecord范围

[英]Rails 5 joining activerecord scopes with OR

I would like to join 2 scopes with OR. 我想用OR加入2个作用域。

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

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

Now I am doing this as I can't figure it out: 现在我正在这样做,因为我无法弄清楚:

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

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

Joining scopes using OR condition is not possible. 无法使用OR条件连接作用域。 A scope narrows resultset with some filter. 范围通过某些过滤器缩小了结果集。 Chaining scopes together is equivalent to using scope filters at the same time, ie SQL's AND condition. 将范围链接在一起等效于同时使用范围过滤器,即SQL的AND条件。

For your case when 2 scopes need to be joined with OR you could merge their resultsets: 对于您需要将两个合并范围合并在一起的情况,可以合并其结果集:

Vehicle.unassigned.to_a | Vehicle.driverless.to_a

but it's better to write another scope, as you already did. 但是最好像您已经写过的那样编写另一个作用域。

这是您要找的东西吗?

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

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

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