PostgreSQL:选择所有关联记录都符合条件的记录

3

我有:

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。通常,我会这样做:

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

但是这将检索符合条件的至少一个b,而不是所有的b。有什么想法吗?
1个回答

3
我会寻找没有matches: false实例的记录。我可能会使用子查询,类似于...
A.joins(:bs).where('(select count(*) from bs where matches = false) = 0')

但是可能有一种更符合ActiveRecord方式的做法。

不是一个坏主意,但 PG 对于在 WHERE 语句中放置什么有点过于抱怨了(ActiveRecord :: StatementInvalid:PG :: GroupingError:ERROR:WHERE 中不允许使用聚合函数) - ichigolas
@nicooga 嗯。我不知道具体的语法,但我认为检查 count(false) == 0 要比检查 count(true) == count(*) 更容易。 - user229044

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接