0
레일의 루비에 중첩 된 양식을 구축 중입니다.has_one 중첩 연결이 편집 경로의 외래 키를 무효화합니다.
중첩 된 연결을 추가하면 정상적으로 작동합니다. 그러나 편집 페이지를로드 할 때 중첩 된 연관의 외래 키 company_id
이 무효화됩니다.
나는 에서 update_only: true
을 시도했으며 다음을 포함합니다. id는 strong params에서 stackoverflow와 유사한 질문에 제안되어 있지만 아무 것도 작동하지 않습니다.
실제로 중첩 된 연관을 업데이트하여 자체 외래 키를 무효화시키는 원인이 무엇인지 말해 줄 수 있습니까? 내 코드는 다음과 같습니다. 감사!
# company.rb
class Company < ApplicationRecord
has_one :mission
accepts_nested_attributes_for :mission, update_only: true
end
# mission.rb
class Mission < ApplicationRecord
belongs_to :company, optional: true
validates :description, presence: true, length: { maximum: 100 }
end
# companies_controller.rb
class CompaniesController < ApplicationController
def edit
@company = Company.find(params[:id])
@company.build_mission if @company.build_mission.nil?
end
def update
@company = Company.find(params[:id])
@company.assign_attributes(company_params)
if @company.valid?
@company.save
redirect_to companies_path
end
end
private
def company_params
params.require(:company).permit(mission_attributes: [:id, :description, :_destroy])
end
end
# edit.html.erb
<%= form_for @company, :url => company_path(@company), :html => {class: 'ui form', method: :put} do |f| %>
<%= f.fields_for :mission do |mission| %>
<div class="field">
<%= mission.label :mission %>
<%= mission.text_field :description %>
</div>
<% end %>
<%= f.button :submit => "", class: "ui button" %>
<% end %>