[英]How to fetch records with exactly specified has_many through records?
我覺得我已經閱讀了所有的“ has_many through”問題,但是沒有一個問題可以幫助我。
所以我通過這樣的設置有一個標准的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}")
但是,它不起作用,它還會使用戶連接到更多產品。
我還開玩笑合並范圍,但沒有得到任何結果。
所有提示表示贊賞! :)
select * from users
join product_associations on product_associations.user_id = users.id
where product_associations.product_id in (2,3)
and not exists (
select *
from product_associations AS pa
where pa.user_id = users.id
and pa.product_id not in (2,3)
)
group by product_associations.user_id
having count(product_associations.product_id) = 2
它有兩件事,找到具有以下條件的用戶:1)所有產品關聯,以及2)沒有其他產品關聯。
Sqlfiddle示例: http ://sqlfiddle.com/#!2/aee8e/5
可以通過Railsified™(某種程度上)實現:
User.joins(:product_associations)
.where(product_associations: { product_id: products })
.where("not exists (select *
from product_associations AS pa
where pa.user_id = users.id
and pa.product_id not in (?)
)", products.pluck(:id))
.group('product_associations.user_id')
.having('count(product_associations.product_id) = ?', products.count)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.