2013-05-30 34 views
0

假设我有Post,Category和Categorizations模型。Rails ActiveRecord:在多个值中搜索多个值

帖子可以通过分类有很多类别。

现在,我该如何取出所有匹配类别数组中至少一项的所有帖子?

实施例:

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和2。

谢谢!

回答

1

假设Categorization是加入模型PostCategory

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

如果不是,和Categorization实际上has_many :categories则:

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

注意,第二个方法将在第一工作大小写也是如此,但它需要2个SQL连接,因此可能无法正常工作。