나는 고치 보석에있는 튜토리얼을 진행할 것입니다. 화장실을 만들려고 할 때 내가 추가하는 시설은 화장실이 먼저 만들어지지 않으면 저장되지 않습니다. 나는 그것이 함께 만들어 져야한다고 생각하고 있었다. 화장실을 만들 때 시설을 구할 수있는 방법이 있습니까?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>
,
짧은 버전, 예 동시에 ... 롱 버전을 모두 절약 할 수 있습니다 : 일반적으로, 당신은 확실히, 새로운 행동을 불러 동적으로 이제까지 기록을 커밋하기 전에 필드를 추가 할 수 있습니다 - 다음 부모 모두 저장 & 중첩 된 필드/모델을 처음으로. – Mirv