首页 > 解决方案 > Rails 6嵌套属性,销毁记录的唯一性验证失败

问题描述

我在验证嵌套属性的唯一性时遇到了问题。我有 2 个模型

#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 对于CompanyStoreBrand应该是唯一的。如果我从一家商店删除品牌并分配给另一家商店,则会引发异常,因为它没有被破坏。以下是我发送的参数

    "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] }])

我在 stackoverflow 上看到了很多解决方案,但其中一些效率低下,或者不支持此标准。有没有其他方法可以实现这一目标?

标签: ruby-on-railsvalidationnested-attributesaccepts-nested-attributesruby-on-rails-6.1

解决方案


推荐阅读