如何找到所有具有 many_to_many 属性的 ActiveRecord 对象,该集合包含具有指定数组的所有关联对象
How to find all ActiveRecord objects which have for a many_to_many attribute a collection that contains all associated objects with specified array
我有 2 个与 has_and_belongs_to_many 关系关联的 ActiveRecord 对象:文章和标签。
我想 select 所有带有名称 foo 和 bar 标签的文章。
我正在尝试执行以下语句,但没有成功。任何帮助表示赞赏。
# gives me non-inclusive associated articles.
Article.joins(:tags).where(tags: {name: ['foo','bar']})
编辑:进一步解释的伪代码:
article_one.tags = ['foo', 'bar'] # want this one only
article_two.tags = ['foo', 'baz'] # no good
article_three.tags = ['bar', 'baz'] # no good
上面的陈述给了我所有三个:(
你应该使用 group
,像这样:
Article.joins(:tags).where(tags: {name: %w(foo bar)}).group('articles.id').having('count(*) = ?', 2)
如果您使用 join
并且有多个 tags
名称 foo
或 bar
附加到特定文章,则将有两行带有此结果中的文章。因此,您只需按 article id
(或任何其他唯一键,但主键在这里最方便)和 return 仅对计数等于 2
的结果进行分组(即你的两个标签都附上了)。
我有 2 个与 has_and_belongs_to_many 关系关联的 ActiveRecord 对象:文章和标签。
我想 select 所有带有名称 foo 和 bar 标签的文章。
我正在尝试执行以下语句,但没有成功。任何帮助表示赞赏。
# gives me non-inclusive associated articles.
Article.joins(:tags).where(tags: {name: ['foo','bar']})
编辑:进一步解释的伪代码:
article_one.tags = ['foo', 'bar'] # want this one only
article_two.tags = ['foo', 'baz'] # no good
article_three.tags = ['bar', 'baz'] # no good
上面的陈述给了我所有三个:(
你应该使用 group
,像这样:
Article.joins(:tags).where(tags: {name: %w(foo bar)}).group('articles.id').having('count(*) = ?', 2)
如果您使用 join
并且有多个 tags
名称 foo
或 bar
附加到特定文章,则将有两行带有此结果中的文章。因此,您只需按 article id
(或任何其他唯一键,但主键在这里最方便)和 return 仅对计数等于 2
的结果进行分组(即你的两个标签都附上了)。