[英]postgresql: select records where ALL associated records match condition
I have: 我有:
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
So I want to implement an scope for A
that retrieves the As where all it's associated Bs matches=true
. 因此,我想为
A
实现一个范围,该范围检索与所有关联的Bs matches=true
的As。 Normally, I would do something like: 通常,我会做类似的事情:
A.joins(:bs).where(bs: { matches: true })
But this will retrieve As where at least one b matches the conditions, not all . 但这将检索到至少一个 b符合条件(不是全部)的 As。
Ideas? 想法?
I would instead look for records where there are zero instances of matches: false
. 相反,我将查找
matches: false
为零的记录matches: false
。 I'd probably use a sub-query, something like... 我可能会使用子查询,例如...
A.joins(:bs).where('(select count(*) from bs where matches = false) = 0')
But there might be a more ActiveRecord way of doing it. 但是可能会有更ActiveRecord的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.