0
我正在rails上構建一個嵌入式表單。has_one嵌套關聯無效編輯路徑上的外鍵
添加嵌套has_one
協會工作正常。但是,當我加載編輯頁面時,嵌套關聯的外鍵company_id
無效。
我試過update_only: true
在accepts_nested_attributes_for
,其中包括:在強大的參數中的id,如在其他類似的回答問題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 %>