简体   繁体   中英

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 . 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 .

Ideas?

I would instead look for records where there are zero instances of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM