Relationship Through Many-To-Many ActiveRecord

1

I have the following configuration in rails:

Company

 has_many :company_products
 has_many :products, :through => :company_products

Product

 has_many :company_products
 has_many :companies, :through => :company_products

ProductGroup

 has_many :company_products

CompanyProduct

 belongs_to :company
 belongs_to :product
 belongs_to :product_group

I need to validate whenever I create the Company or Product if it contains a CompanyProduct too.

How can I validate the CompanyProduct by Company or Product ?

    
asked by anonymous 13.09.2016 / 22:00

1 answer

0

In a has_many throught relationship, you can use uniq to ensure that duplicate relationships are not created. It would look something like:

Company

 has_many :company_products
 has_many :products, -> { uniq }, :through => :company_products

Product

 has_many :company_products
 has_many :companies, -> { uniq }, :through => :company_products

ProductGroup

 has_many :company_products

CompanyProduct

 belongs_to :company
 belongs_to :product
 belongs_to :product_group
    
14.09.2016 / 14:13