0

Ruby on Rails를 사용하여 중첩 된 양식을 작성했습니다. 세 테이블 (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

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

:_delete 당신에게 너무 많은 Mr.Steve 감사 동의를 확인합니다. 그것은 효과가 있었다. 또 다른 의심은 언제 user.contact.build를 사용해야합니까? – poombavai

+1

'my_object.build_something'은'my_object'와'something' 사이에 일대일 연관이있을 때 사용하고,'my_object.somethings.build'는'my_object'와'something' 사이의 일대 다 연관 일 때 사용합니다 – SteveTurczyn

+0

Mr.Steve를 명확히 해 주셔서 감사합니다. – poombavai