2

나는 모든 "so_many through"질문을 읽은 것 같지만 아무도 내 문제를 해결하지 못했다. ,레코드를 통해 정확히 has_many가 지정된 레코드를 가져 오는 방법은 무엇입니까?

제품의 A, B에 제품 관련이있는 모든 사용자를 찾기 :

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, 내가 원하는 것은 아주 간단합니다 :

그래서 나는이 같은 설정을 통해 표준 has_many이 와 C, 더 이상,

이 그래서 제품의 부부가없고 그들이 shouldn (정확히 해당 제품에 연결된 모든 사용자를 찾으려면 더 적은 '없다 다른 제품과의 다른 제품 연결이 있음). 더 많은 제품에 연결

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으로 장난 꾸러기지만 어떤 결과도 얻지 못했습니다.

모든 힌트를 환영합니다! :)

+0

잘 모든 - 그래서 주문이 하나 개의 제품을 가질 수있다? –

+0

그것은 단지 인위적인 예였습니다. 나는 수업을 업데이트했는데 잘하면 지금은 분명해. –

+0

내 대답이 업데이트되었습니다. –

답변

1
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) 
+0

아니요, has_and_belongs_to_many는 has_many through와 다릅니다. –

+0

레코드 (말장난 의도)의 경우, 'has_and_belongs_to_many'는 두포에서'has_many through'와 거의 동일합니다. –

+0

* 한숨 * 나는 snarky "가짜 코드"발언을 무시하겠다. 코드가 작동하지 않아도 여전히 두 제품이 넘는 사용자가 반환됩니다. –

관련 문제