2014-10-01 104 views
1

我:PostgreSQL的:選擇記錄,其中的所有相關記錄匹配條件

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檢索,其中所有它相關的燒烤matches=true了作爲一個範圍。通常情況下,我會做這樣的事情:

A.joins(:bs).where(bs: { matches: true }) 

但是,這將檢索作爲其中至少一個 B中的條件,不是所有匹配

想法?

回答

2

我會查找記錄,其中有零個實例matches: false。我可能會使用一個子查詢,類似...

A.joins(:bs).where('(select count(*) from bs where matches = false) = 0') 

但是可能有更ActiveRecord的方式來做到這一點。

+0

不是一個壞主意,但是PG對於你放入的WHERE語句有什麼不滿(ActiveRecord :: StatementInvalid:PG :: GroupingError:ERROR:集合函數在WHERE中是不允許的) – nicooga 2014-10-02 14:20:21

+0

@nicooga嗯。我不知道具體的語法,但是我必須假設檢查'count(false)== 0'比'count(true)== count(*)'更容易。 – meagar 2014-10-02 14:29:34

相關問題