我遇到了类似的错误
通过关联在我的ActiveRecord::RecordNotUnique Exception
中has_many
class Customer < ActiveRecord::Base
has_many :customers_sellers, dependent: :destroy
has_many :sellers, through: :customers_sellers
end
class Seller < ActiveRecord::Base
has_many :customers_sellers, dependent: :destroy
has_many :customers, through: :customers_sellers
end
class CustomersSeller < ActiveRecord::Base
belongs_to :customer
belongs_to :seller
end
在为特定卖家创建客户时,我遇到了一个错误
CustomersSeller.create()
行。
Error: ActiveRecord::RecordNotUnique Exception
在我的has_many中通过关联。
重复键违反了唯一约束“ customers_sellers_pkey”。
答案 0 :(得分:0)
这解决了我的问题:
begin
CustomersSeller.where(seller_id: @seller.id, customer_id: @customer.id).first_or_create(seller: @seller, customer: @customer, customer_name: @customer.try(:business_name), status: "Invited")
rescue ActiveRecord::RecordNotUnique
retry
end