2017-06-29 5 views
0

モデルのユーザー作成:レール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 %> 

フォームを送信すると、すべて正常であると表示されますが、「更新は成功しました」という意味ですが、新しいレコードがアドレステーブルに追加されたように見えますが、ユーザーテーブルは正しく更新されます。誰かがなぜ私に説明を与えることができますか?私はGoogleで答えを探していますが、何も私を助けません。私は自分のフォームを送信すると、それはすべてが正常である私を示し、私は意味 は「成功した更新」

答えて

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 
関連する問題