Skip to main content
 首页 » 编程设计

ruby-on-rails之无法为 has_one 关联更新我的嵌套模型表单

2025年02月15日38jpfss

我尝试为 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 

我的用户 Controller :
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
知道错误在哪里吗?谢谢

请您参考如下方法:

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

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