2017-06-29 51 views
0

型号用户:的Rails 5.协会一对一,更新记录建立新的

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 %> 

当我提交我的表单时,它显示我一切都很好,我的意思是“更新成功”,但在数据库中它看起来像新记录被添加到地址表中,但用户表已正确更新。有人可以给我解释为什么?我在谷歌寻找答案,但没有任何帮助我。

回答

0

当我提交我的形式,它显示我一切都很好,我的意思是 “成功更新”,但在数据库中它看起来像新的记录是 添加到地址表,但用户表是否正确更新。可以 有人给我解释为什么?

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