【发布时间】:2015-04-28 06:46:15
【问题描述】:
我有两个模型,Item 和 Category,由一个连接表连接。我想查询 Item 以仅查找与类别列表匹配的项目。我的模型看起来像:
class Item < ActiveRecord::Base
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :items
end
我可以轻松找到与任何类别列表匹配的项目。以下将返回属于类别 1、2 或 3 的项目。
Item.includes(:categories).where(categories: {id:[1,2,3]})
我只想查找属于所有 3 个类别的项目。使用 ActiveRecord 完成此任务的最佳方法是什么?
我是否需要自己编写 where 条件,如果需要,PostgreSQL 的正确语法是什么?我尝试了各种风格的“WHERE ALL IN (1,2,3)”,但只是得到语法错误。
更新:
根据对Find Products matching ALL Categories (Rails 3.1) 的接受回答,我可以非常接近。
category_ids = [7,10,12,13,52,1162]
Item.joins(:categories).
where(categories: {id: category_ids}).
group('items.id').
having("count(categories_items.category_id) = #{category_ids.size}")
不幸的是,当链接 .count 或 .size 时,我得到一个哈希而不是记录计数:
{189 => 6, 3067 => 6, 406 => 6}
我可以计算结果哈希中的键来获得真正的记录数,但这是一个非常不优雅的解决方案。
【问题讨论】:
标签: ruby-on-rails ruby postgresql rails-activerecord