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

时间:2017-06-29 05:37:34

标签: ruby-on-rails associations one-to-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 %>

当我提交表单时,它显示一切正常,我的意思是&#34;更新成功&#34;,但在数据库中,它看起来像新记录被添加到地址表,但用户表正确更新。有人可以给我解释原因吗?我正在谷歌寻找答案,但没有任何帮助我。

2 个答案:

答案 0 :(得分:0)

  

当我提交表单时,它表明我的一切都很好,我的意思是   &#34;更新成功&#34;,但在数据库中它看起来像新记录   添加到地址表,但用户表已正确更新。能够   有人给我解释原因?

这是由于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

答案 1 :(得分:0)

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

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