Rails 5.一对一关联,更新记录新建一个

Rails 5. Association one to one, updating record create new one

模范用户:

class User < ApplicationRecord
  has_one :address, foreign_key: :user_id
  accepts_nested_attributes_for :address
end

模型地址

class Address < ApplicationRecord
  belongs_to :user, optional: true
end

控制器用户,一切都发生在这里

class UsersController < ApplicationController
   def home # method which I use to display form
     @user = User.find_by :id => session[:id]
   end

   def update # method for updating data
     @user = User.find(session[:id])
     if @user.update(user_params)
       flash[:notice] = "Update successfully"
       redirect_to home_path
     else
       flash[:error] = "Can not update"
       redirect_to home_path
     end
   end

   private
     def user_params
       params.require(:user).permit(:name, :email, :password, images_attributes: [:image_link, :image_description], address_attributes: [:city, :street, :home_number, :post_code, :country])
     end
end

更新表格:

<%= form_for @user, :html => { :id => "update-form", :class => "update-form"} do |f| %>
  <%= f.text_field :name %>
  <%= f.text_field :email %>
  <%= f.fields_for :address do |a| %>
    <%= a.text_field :city %>
    <%= a.text_field :street %>
    <%= a.number_field :home_number %>
    <%= a.text_field :post_code %>
    <%= a.text_field :country %>
  <% end %>
  <%= f.submit %>
<% end %>

当我提交表单时,它显示一切正常,我的意思是 "Update successfully",但在数据库中它看起来像新记录添加到地址 table,但用户 table 已正确更新。有人可以给我解释为什么吗?我正在 google 中寻找答案,但没有任何帮助。

When I submitting my form, it shows me everything is fine, I mean "Update successfully", but in database its looks like new record is added to address table, but user table is updated properly. Can someone give me explanation why?

这是 strong params 的性质所致。它希望 :id 被允许 以便 nested_attributes 正确更新,否则会创建一个新记录。允许 :id 就可以了。

def user_params
  params.require(:user).permit(:name, :email, :password, images_attributes: [:id, :image_link, :image_description], address_attributes: [:id, :city, :street, :home_number, :post_code, :country])
end

在控制器中尝试以下代码:

class UsersController < ApplicationController
   def home # method which I use to display form
     @user = User.find_by :id => session[:id]
   end

   def update # method for updating data
     @user = User.find(session[:id])
     if @user.update(user_params)
       flash[:notice] = "Update successfully"
       redirect_to home_path
     else
       flash[:error] = "Can not update"
       redirect_to home_path
     end
   end

   private
     def user_params
       params.require(:user).permit(:name, :email, :password, images_attributes: [:image_link, :image_description], address_attributes: [:id, :city, :street, :home_number, :post_code, :country])
     end
end