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