代码之家  ›  专栏  ›  技术社区  ›  Sean Magyar

Rails 5将activerecord作用域与或连接起来

  •  2
  • Sean Magyar  · 技术社区  · 8 年前

    我想加入两个范围与或。

    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
      )
    }
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   Ilya Konyukhov    8 年前

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

    无法使用或条件连接作用域。作用域通过一些过滤器缩小结果集。将作用域链接在一起相当于同时使用作用域过滤器,即SQL和condition。

    对于需要连接2个作用域或可以合并其结果集的情况:

    Vehicle.unassigned.to_a | Vehicle.driverless.to_a
    

    但最好还是写另一个作用域,就像你已经做的那样。

        2
  •  -1
  •   YJ Zhang    8 年前

    这就是你要找的吗?

    scope :inactive, -> { unassigned.or(driverless) }
    
    推荐文章