Relationship Through Many-To-Many Activerecord

Asked

Viewed 84 times

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 every time I create the Company or Product contains a CompanyProduct also.

How can I validate CompanyProduct by the Company or Product ?

1 answer

0

In a relationship has_many throught you can use the uniq to ensure that duplicated relationships will not be 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.