나는 모든 "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으로 장난 꾸러기지만 어떤 결과도 얻지 못했습니다.
모든 힌트를 환영합니다! :)
잘 모든 - 그래서 주문이 하나 개의 제품을 가질 수있다? –
그것은 단지 인위적인 예였습니다. 나는 수업을 업데이트했는데 잘하면 지금은 분명해. –
내 대답이 업데이트되었습니다. –