1

我正在尝试从 A 返回记录,其中来自 B 的所有匹配记录都满足条件。目前,我的查询返回来自 A 的记录,其中有来自 B 的任何记录满足条件。让我把它放到一个真实世界的场景中。

Post.joins(:categories)
    .where(:categories => { :type => "foo" })

这将返回Post具有“foo”类型类别的 s,我想要的是Posts,其类别都是“foo”类型!

帮助表示赞赏!

4

3 回答 3

2

使用您在 IRC 上 #rubyonrails 中发布的 db/schema.rb,例如:

Incident.select("incidents.id").
joins("INNER JOIN category_incidents ON category_incidents.incident_id = incidents.id").
joins("INNER JOIN category_marks ON category_marks.category_id = category_incidents.category_id").
where(:category_marks => { :user_group_id => current_user.user_group_id }).
group("incidents.id").
having("SUM(CASE WHEN category_marks.inc = 1 THEN 1 ELSE 0 END) = count(category_indicents.incident_id)")

会成功的。

它连接 current_user 的 category_marks 并检查 .inc = 1 的记录计数是否等于所有连接记录的计数。

请注意,这只获取 event.id

于 2013-03-15T13:09:31.753 回答
1

我会在此查询的末尾添加一个选择,以检查所有类别是否都具有 foo 类型。我还将通过向 Category 模型添加一个实例方法来简化该检查。

Post.joins(:categories).select{|p| p.categories.all?(&:type_foo?)}

类别模型

 def type_foo?
   type == "foo"
 end

添加:这有点“hacky”,但您可以通过这种方式将其设为范围。

class Post < ActiveRecord::Base
  scope :category_type_foo, lambda{ 
    post_ids = Post.all.collect{|p| p.id if p.categories.all?(&:type_foo?).compact
    Post.where(id: post_ids) }
end
于 2013-03-15T12:10:34.370 回答
0

您是否尝试过反方向的查询?IE

Categories.where(type: 'foo').joins(:posts)

不过我可能误解了你的问题。

另一种选择是

Post.joins(:classifications).where(type: 'foo')
于 2013-03-15T12:30:26.033 回答