所以,假设我有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和帖子。
谢谢!
答案 0 :(得分:1)
假设Categorization
是Post
和Category
的加入模型:
Post.joins(:categorizations).where(:categorizations => {:category_id => [3, 5]})
如果不是,Categorization
实际上has_many :categories
那么:
Post.joins(:categories).where(:categories=> {:id => [3, 5]})
请注意,第二种方法也适用于第一种情况,但是它需要2个SQL连接,因此可能无法正常运行。