簡體   English   中英

postgresql:選擇所有相關記錄都符合條件的記錄

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM