无法更新has_one关联的嵌套模型表单

我尝试为has_one关联创建一个嵌套的模型表单。 (我正在使用Rails 4)

在我的用户和地址模型中,我有以下内容:

class User < ActiveRecord::Base has_one :address accepts_nested_attributes_for :address end class Address < ActiveRecord::Base belongs_to :user end 

我的用户控制器:

 class UsersController < ApplicationController . . . def edit @user = User.find(params[:id]) @user.build_address if @user.address.nil? end def update @user = User.find(params[:id]) if @user.update(params.require(:user).permit(:user_name, address_attributes: [:street])) flash[:success] = "Profile updated successfully" sign_in @user redirect_to @user else flash.now[:error] = "Cannot updating your profile" render 'edit' end end end 

终于在我看来我有:

 = form_for(@user) do |f| = render 'shared/error_messages', object: f.object %div = f.label :user_name, "User name" = f.text_field :user_name = f.fields_for :address do |add| = addd.label :street = d.text_field :street = f.submit "Update" 

当我第一次尝试填充街道文件时它可以工作,但当我尝试更新时我得到错误: Failed to remove the existing associated address. The record failed to save after its foreign key was set to nil Failed to remove the existing associated address. The record failed to save after its foreign key was set to nil

任何想法错误在哪里? 谢谢

在您的控制器UsersController ,在update方法中,将address: :id添加到允许的地址属性中。 像这样:

 params.require(:user).permit(:user_name, address_attributes: [:id, :street])) 

如果记录已存在,可以选择进行部分更新:

 accepts_nested_attributes_for(:address, update_only: true) 

记录在这里: http : //api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for

此错误通常表示has_one关系存在现有记录。 换句话说,该特定user对象已经具有与之关联的address记录。 在浏览器中测试表单时可能会发生这种情况。

在这种情况下,似乎Rails正在尝试创建一个新的地址记录,它与编写动作的编写方式有关。

试试这个:

 def edit @user = User.find(params[:id]) @address = user.address || @user.build_address end