Rails 4 - 多态关联与嵌套多态属性的更新操作

Rails 4 - Polymorphic associations with update action on nested polymorphic attributes

我正在尝试找出我在 Rails 4 应用程序中设置多态关联时似乎一直遇到的问题。

我有一个项目模型和一个地址模型。这些协会是:

简介

has_many :addresses, as: :addressable
    accepts_nested_attributes_for :addresses,  reject_if: :all_blank, allow_destroy: true

地址

belongs_to :addressable, :polymorphic => true

我之前就同样的问题问过这个问题。我无法(现在仍然无法)理解 post 中的答案:Rails 4 - Polymorphic associations

这一次 - 我遇到了一个问题,当我尝试通过插入地址来更新个人资料时触发了这个问题。错误消息将问题标识为来自配置文件控制器中的更新操作。更新操作有:

我的配置文件控制器更新操作有:

def update

    # successful = @profile.update(profile_params)

    # Rails.logger.info "xxxxxxxxxxxxx"
    # Rails.logger.info successful.inspect
    # user=@profile.user
    # user.update.avatar
    # Rails.logger.info "prof xxxxxxxxxxxxx"
    # Rails.logger.info @profile.update(profile_params)
    respond_to do |format|
      if @profile.update(profile_params)
        format.html { redirect_to @profile }
        format.json { render :show, status: :ok, location: @profile }
      else
        format.html { render :edit }
        format.json { render json: @profile.errors, status: :unprocessable_entity }
      end
    end
  end

错误消息说:

ERROR:  duplicate key value violates unique constraint "index_addresses_on_addressable_type_and_addressable_id"
DETAIL:  Key (addressable_type, addressable_id)=(Profile, 1) already exists.

有谁知道这条消息是什么意思,如何解决?

在你的数据库中,你设置了一个唯一约束: ,你可以到数据库中查看你设置的名字"index_addresses_on_addressable_type_and_addressable_id"。如错误消息所示,您尝试使用已被另一条记录使用的值 ( Profile , 1) 更新记录。
要解决此问题,有两种解决方案: 一个来自数据库端: 您需要知道为什么地址有唯一约束。如果不需要,您可以将其从数据库中删除。 另一个是在将数据更新到数据库之前确保 (addressable_type, addressable_id) 是唯一的。

希望能给到一点帮助