Rails ActiveRecord:使用多个值搜索多个值

时间:2013-05-30 01:12:07

标签: ruby-on-rails activerecord associations

所以,假设我有Post,Category和Categorizations模型。

通过分类,帖子可以包含多个类别。

现在,我如何提取所有与一组类别中的至少一项相匹配的帖子?

示例:

Post 1 has categories 2,5,6
Post 2 has categories 1,5,9
Post 3 has categories 2,4,8
Find posts that match 3,5

我想要回复帖子1和帖子。

谢谢!

1 个答案:

答案 0 :(得分:1)

假设CategorizationPostCategory的加入模型:

Post.joins(:categorizations).where(:categorizations => {:category_id => [3, 5]})

如果不是,Categorization实际上has_many :categories那么:

Post.joins(:categories).where(:categories=> {:id => [3, 5]})

请注意,第二种方法也适用于第一种情况,但是它需要2个SQL连接,因此可能无法正常运行。