[英]postgresql: select records where ALL associated records match condition
我有:
class A < ActiveRecord::Base
has_many :abs
has_many :bs, through: :abs
end
class AB
belongs_to :a
belongs_to :b
end
class B < ActiveRecord::Base
has_many :abs
has_many :as, through: :abs
# and has boolean db field :matches
end
因此,我想為A
實現一個范圍,該范圍檢索與所有關聯的Bs matches=true
的As。 通常,我會做類似的事情:
A.joins(:bs).where(bs: { matches: true })
但這將檢索到至少一個 b符合條件(不是全部)的 As。
想法?
相反,我將查找matches: false
為零的記錄matches: false
。 我可能會使用子查詢,例如...
A.joins(:bs).where('(select count(*) from bs where matches = false) = 0')
但是可能會有更ActiveRecord的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.