繁体   English   中英

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

我之前曾在同一问题上问过这个问题。 我无法(仍然无法)理解该帖子中的答案: Rails 4-多态关联

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

我的个人档案控制器更新操作包括:

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)是唯一的。

希望这可以提供帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM