has_one嵌套关联使编辑路由上的外键无效

时间:2017-02-10 17:32:55

标签: ruby-on-rails nested-attributes has-one

我正在轨道上的ruby中构建一个嵌套表单。

添加嵌套的has_one关联可以正常工作。但是,当我加载编辑页面时,嵌套关联的外键company_id无效。

我在update_only: true中尝试了accepts_nested_attributes_for并且包括:在强大参数中的ID,如堆栈溢出中其他类似的已回答问题所示,但对我来说没有任何作用。

有人能告诉我实际上是什么导致嵌套关联更新并使其外键本身无效?我的代码如下所示。谢谢!

# 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 %>

1 个答案:

答案 0 :(得分:0)

嘿,我设法在睡个好觉后解决问题。事实证明,我只需要在公司控制器级别处理if else条件。编辑方法应修改为: -

def edit
  @company = Company.find(params[:id])
  if @company.mission
  else
    @company.build_mission
  end
end