嵌套属性显示编辑时,但不显示在rails

时间:2017-11-16 16:36:33

标签: ruby-on-rails-4 activerecord nested-forms

当我使用嵌套属性编辑模型时,一切都很完美。如果我尝试使用嵌套属性创建新记录,嵌套属性不会出现在具有嵌套属性的表单上。我有两个模型如下

class JobSpec < ActiveRecord::Base
  has_many :availabilities
  accepts_nested_attributes_for :availabilities, allow_destroy: true
end

class Availability < ActiveRecord::Base
  belongs_to :job_spec
end

job_specs_controller我有

class JobSpecsController < ApplicationController
  def new
    @job_spec = JobSpec.new
    @availabilities = Availability.none
    availability = Availability.new
    availability.job_spec = @job_spec
    @availabilities << availability
  end

  def edit
    @job_spec = JobSpec.find(params[:id])
    @availabilities = @job_spec.availabilities
  end

  def job_spec_params
    params.require(:job_spec).permit(
      ... all of the job_spec attributes,
      availabilities_attributes: [:id, ... all of the availability attributes],
    )
  end
end

_form job_spec我有

  <% @availabilities.each do |availability| %>
    <%= f.fields_for availability do |builder| %>
      <%= render partial: 'availabilities/form_mini', 
        locals: {f: builder, availability: availability} %>
    <% end %>
  <% end %>

由于编辑工作,我认为没有太大的错误。有什么想法吗?

更新

我几乎已经解决了所有问题,但仍然有一个问题。这就是我所做的。

1)我必须构建job_spec availabilitiesJobSpecsController的新操作现在看起来像这样

  def new
    @job_spec = JobSpec.new
    @job_spec.client_id = params[:client_id]
    @job_spec.availabilities.build
  end

2)我希望能够销毁嵌套模型,因此我必须将嵌套属性:_destroy传递给job_spec_params。该方法看起来像这样

  def job_spec_params
    params.require(:job_spec).permit(
      ... all of the job_spec attributes,
      availabilities_attributes: [:id, :_destroy, ... all of the availability attributes],
    )
  end
end

3)最后,我必须为_form更改job_spec。我有

<%= f.fields_for :availabilities do |builder| %>
  <%= render partial: 'availabilities/form_mini', locals: {f: builder} %>
<% end %>

我现在唯一的问题是我想将实例变量传递给我的可用部分。像这样的东西

<%= render partial: 'availabilities/form_mini', locals: {f: builder, a: availability} %>

应该怎么做?我不知道如何在渲染所有部分时迭代所有@availabilities

1 个答案:

答案 0 :(得分:0)

很高兴你解决了一些问题。第一个小改进

#job_specs_controller.rb

def new
  @job_spec = JobSpec.new(client_id: params[:client_id])
  @job_spec.availabilities.build
end

为了克服你的上一个问题,解决方案是你之前和之后的混合。您可以在fields_for方法中传递实际对象。它是这样的:

#_form.html.erb
<% @job_spec.availabilities.each do |availability| %>
  <%= f.fields_for :availabilities, availability do |builder| %>
    <%= render partial: 'availabilities/form_mini',
        locals: {f: builder, a: availability} %>
  <% end %>
<% end %>