0

Ruby on Railsを使用してネストされたフォームを構築しました。 私は3つのテーブル(User, Contact, Address)のフィールドを持つフォームを作成しようとしています。ユーザー表はaddress_idcontact_idです。ユーザーが詳細を入力すると、連絡先の詳細はcontactテーブルに保存され、アドレスはaddressテーブルに保存されます。両方のIDは、ユーザーの詳細とともにユーザーテーブルに保存される必要があります。私はどのように進めるべきですか? レールを使用してネストされたフォームに値を保存できませんでした5

私のモデル

class Address < ApplicationRecord 
    has_one :user 
end 

class Contact < ApplicationRecord 
    has_one :user 
end 

class User < ApplicationRecord 
    belongs_to :address 
    belongs_to :contact 
end 

私のコントローラ、

class UsersController < ApplicationController 
    def new 
    @user = User.new 
    @user.build_contact 
    @user.build_address 
    end 
    def create 
    @user = User.new(user_params) 
    respond_to do |format| 
     if @user.save 
     format.html { redirect_to @user, notice: 'User was successfully created.' } 
     format.json { render :show, status: :created, location: @user } 
     else 
     format.html { render :new } 
     format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 
    end 
    end 
    private 
    def user_params 
    params.require(:user).permit(:name, :email, contact_attributes: [:phone], address_attributes: [:street, :city]) 
    end 
end 

そして、私の図であり、

<%= form_for(user) do |f| %> 
    <% if user.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2> 
     <ul> 
     <% user.errors.full_messages.each do |message| %> 
     <li><%= message %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= f.label :name %> 
    <%= f.text_field :name %> 
</div> 

<div class="field"> 
    <%= f.label :email %> 
    <%= f.text_field :email %> 
</div> 

<%= f.fields_for :contact do |c| %> 
    <div class="field"> 
    <%= c.label :phone %> 
    <%= c.text_field :phone %> 
    </div> 
<% end %> 

<%= f.fields_for :address do |a| %> 
    <div class="field"> 
    <%= a.label :street %> 
    <%= a.text_field :street %> 
    </div> 

    <div class="field"> 
    <%= a.label :city %> 
    <%= a.text_field :city %> 
    </div> 
<% end %> 

<div class="actions"> 
    <%= f.submit %> 
</div> 
<% end %> 

は私のアプローチは正しいですか?親切にお勧めします。前もって感謝します。

答えて

0

あなたは数行が欠け...

class User < ApplicationRecord 
    belongs_to :address 
    belongs_to :contact 
    accepts_nested_attributes_for :address 
    accepts_nested_attributes_for :contact 
end 

また、あなたが:id:_delete

params.require(:user).permit(:name, :email, contact_attributes: [:id, :phone, :_delete], address_attributes: [:id, :street, :city, :_delete] 
+0

を受け入れる確保そんなにMr.Steveありがとうございます。出来た。もう一つの疑問は、いつuser.contact.buildを使うべきでしょうか? – poombavai

+1

'my_object.build_something'は、' my_object'と 'something'の間に1対1の関連があるときに' my_object.sbuild_something'を使いますが、 'my_object'と' something'の間に1対多の関係があるときは 'my_object.somethings.build'を使います。 – SteveTurczyn

+0

Mr.Steveを明確にしてくれてありがとう。 – poombavai

関連する問題