Reputation: 422
I am facing issue in validating nested attributes uniquness. I have 2 models
#model : CompanyStore
class CompanyStore < ApplicationRecord
has_many :company_stores_brands, dependent: :destroy
accepts_nested_attributes_for :company_stores_brands, allow_destroy: true
end
class CompanyStoreBrand < ApplicationRecord
validates_uniqueness_of :brand_id
end
brand_id should be unique for CompanyStoreBrand . If I remove brand from one store and assign to another store it is throwing an exception because it is not destroyed. Below is params that I am sending
"company_stores_attributes"=>[
{"id"=>1, "store_id"=>446, "company_stores_brands_attributes"=>[{"id"=>1, "_destroy"=>1, "brand_id"=>69258}]},
{"id"=>3, "store_id"=>472, "company_stores_brands_attributes"=>[{"brand_id"=>69258}]}]
params.require(:company).permit(company_stores_attributes: [:id, :store_id, :_destroy,{ company_stores_brands_attributes: %i[id brand_id _destroy] }])
I have seen lot of solutions on stackoverflow but some of them are inefficient Or this criteria is not supported. Is there any other way to achieve this?
Upvotes: 1
Views: 55