mardi 7 mars 2017

How to add uniqueness on many to many using through on column of other table

I have two models Company, Asset and a join model CompanyAsset and the association is as follows:

class Company < ActiveRecord::Base
  has_many :company_assets
  has_many :assets, through: :company_assets    
  accepts_nested_attributes_for :company_assets, allow_destroy: true
end

class Asset < ActiveRecord::Base
  has_many :company_assets
  has_many :companies, through: :company_assets

  validates :label, uniqueness: true
end

class CompanyAsset < ActiveRecord::Base
  belongs_to :company
  belongs_to :asset
  accepts_nested_attributes_for :asset, allow_destroy: true
end

I want to validate uniqueness of label attribute of Asset such that uniqueness is specific to Company.

For ex: There is Company-A and Company-B.

Company-A has one Asset with label Asset-A. Now system should allow me to create Asset-A for Company-B but should not allow to create Asset-A again for Company-A.

validates :label, uniqueness: true will not allow to create Assetwith same label in any Company

I am creating Asset records

a =  Company.find(1) // Company-A
a.update(company_assets_attributes: [{info: 'pqr', asset_attributes: {label: 'Asset A'}}])

Now I want to create Asset-A for Company-B

b = Company.find(2) // Company-B
b.update(company_assets_attributes: [{info: 'abc', asset_attributes: {label: 'Asset A'}}])

Any thoughts on how to handle the uniqueness?

Aucun commentaire:

Enregistrer un commentaire