[英]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.