无法为 has_one 关联更新我的嵌套模型表单 [英] Can't update my nested model form for has_one association

查看:24
本文介绍了无法为 has_one 关联更新我的嵌套模型表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试为 has_one 关联创建嵌套模型表单.(我使用的是 Rails 4)

I try to create a nested model form for the has_one association. (i'm using Rails 4)

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

In my user, and adress model i have the following :

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"

当我第一次尝试填充街道时它可以工作,但是当我尝试更新时,我收到错误:无法删除现有的关联地址.外键设置为nil后记录保存失败

When i try to fill street filed for the first time it works, but when i try to update i get the error : Failed to remove the existing associated address. The record failed to save after its foreign key was set to nil

知道错误在哪里吗?谢谢

any idea where is the error ? thank's

推荐答案

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

in your controller UsersController, in the update method, add the address: :id to the address permitted attributes. Like this:

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

这篇关于无法为 has_one 关联更新我的嵌套模型表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆