2017-03-08 5 views
1

나는 고치 보석에있는 튜토리얼을 진행할 것입니다. 화장실을 만들려고 할 때 내가 추가하는 시설은 화장실이 먼저 만들어지지 않으면 저장되지 않습니다. 나는 그것이 함께 만들어 져야한다고 생각하고 있었다. 화장실을 만들 때 시설을 구할 수있는 방법이 있습니까?cocoon gem을 사용하여 중첩 된 양식을 추가하십시오. 화장실을 먼저 만들지 않으면 시설물을 구할 수 없습니다.

는 일이 혼동되지하려면

class Toilet < ApplicationRecord 
has_many :facilities 
    accepts_nested_attributes_for :facilities, reject_if: :all_blank, allow_destroy: true 
end 

class Facility < ApplicationRecord 
    belongs_to :toilet 
end 

화장실 컨트롤러

def new 
@toilet = Toilet.new 
end 

def create 
@toilet = Toilet.new(toilet_params) 
if @toilet.save 
    redirect_to @toilet 
else 
    render :new 
end 
end 

private 
def toilet_params 
    params.require(:toilet).permit(:name, :location, facilities_attributes: [:id, :name, :_destroy]) 
end 

_form.html.erb

<%= f.simple_fields_for :facilities do |facility| %> 
<%= render 'facility_fields', :f => facility %> 
<% end %> 
<div class='links'> 
<%= link_to_add_association 'add facility', f, :facilities %> 
</div> 
<%= f.submit 'Save' %> 
<% end %> 

_facility_fields.html.erb

<div class='nested-fields'> 
<%= f.inputs do %> 
    <%= f.input :name %> 
    <%= link_to_remove_association "remove facility", f %> 
<% end %> 
</div> 
,
+0

짧은 버전, 예 동시에 ... 롱 버전을 모두 절약 할 수 있습니다 : 일반적으로, 당신은 확실히, 새로운 행동을 불러 동적으로 이제까지 기록을 커밋하기 전에 필드를 추가 할 수 있습니다 - 다음 부모 모두 저장 & 중첩 된 필드/모델을 처음으로. – Mirv

답변

0

웨슬리, 예 - 부모 모두를 동시에 저장할 수 있어야합니다. & 긴 버전 : 네, 새로운 레코드를 생성하기 전에 레코드를 저장하기 전에 중첩 된 내용을 동적으로 추가 할 수 있습니다. 둘 중 하나의 레코드를 동시에 저장하려면 두 레코드를 동시에 저장하십시오.

귀하의 문제는 아마도 _facility_fields.html.erb에있는 것 같습니다 ... <% f.inputs do %>이 보이거나 설정이 잘못되었습니다. render 명령을 포장하는 do 루프가 이미 있으므로이 다른 do 루프가 필요 없습니다. 즉 /div 바로 위에있는 템플릿에서 end 개의 항목을 삭제하고 싶다는 의미입니다.

_facility_fields.html.erb 

<div class='nested-fields'> 
<%= f.inputs do %>    // Issue is this line 
    <%= f.input :name %> 
    <%= link_to_remove_association "remove facility", f %> 
<% end %>      // Remove this too afterwards 
</div> 
+1

그건 내 실수 였어. 이 [여기] (https://www.google.com)에 대한 간단한 해결책을 찾았습니다. Facility 모델에서'belongs_to : toilet, optional : true'를 추가합니다. Rails 5와 관련이 있습니다. – Wesly

+0

귀하의 링크가 구글로 이동합니다. 특정 검색이나 페이지가 아닙니다. 그러나 좋은 sleuthing - 레일 5로 즐거운 시간을 보냈지 만, 옵션 부울을 아직 사용하지 않았습니다. :) – Mirv