【发布时间】:2014-03-18 19:42:26
【问题描述】:
我觉得我已经阅读了所有“通过”的问题,但没有一个对我的问题有帮助。
所以我有一个标准的 has_many 通过这样的设置:
class User < ActiveRecord::Base
has_many :product_associations
has_many :products, through: :product_associations
end
class ProductAssociation < ActiveRecord::Base
belongs_to :user
belongs_to :product
end
class Product < ActiveRecord::Base
has_many :product_associations
has_many :users, through: :product_associations
end
IMO,我想要的很简单:
查找与产品 A、B 和 C 有产品关联的所有用户,不多也不少
所以我有几个产品,想找到所有与正是这些产品相关的用户(他们不应该与其他产品有任何其他产品关联)。
这是我想出的最好的:
products # the array of products that I want to find all connected users for
User
.joins(:product_associations)
.where(product_associations: { product_id: products.map(&:id) })
.group('products.id')
.having("COUNT(product_associations.id) = #{products.count}")
但它不起作用,它还会返回连接到更多产品的用户。
我也玩弄了merging scopes,但没有得到任何结果。
感谢所有提示! :)
【问题讨论】:
-
您的架构似乎完全不正确——所以一个订单只能有一个产品?
-
这只是一个人为的例子。我更新了课程,希望现在更清楚了。
标签: ruby-on-rails ruby-on-rails-3 activerecord has-many-through