Rails:将嵌套表单拆分为部分

时间:2017-10-24 21:52:56

标签: ruby-on-rails ruby-on-rails-5

我有一个完全正常的嵌套表单,但是,我正在试图找出如何将嵌套表单拆分为部分表单。

原始形式:

  <%= form_for(@user) do |f| %>

    <%= f.fields_for :achievements, Achievement.new do |ff| %>

    <div class="field">
      <%= ff.label :certification_name, 'Cert Name' %>
      <%= ff.text_field :certification_name %>       
    </div>

    <% end %><!-- fields_for -->

    <%= f.submit 'Save', id: "submit-achievement", class: 'btn btn-primary' %> 

这就是我要做的......

  <%= form_for(@user) do |f| %>

    <%= f.fields_for :achievements, Achievement.new do |ff| %>

      <%= render partial: 'achievements/new_certification' %>

    <% end %><!-- fields_for -->

    <%= f.submit 'Save', id: "submit-achievement", class: 'btn btn-primary' %>

这是部分。

<div class="field">
  <%= ff.label :certification_name, 'Cert Name' %>
  <%= ff.text_field :certification_name %>       
</div>

问题在于它不知道如何处理'ff'变量。

ActionView::Template::Error (undefined local variable or method `ff' for #<#<Class:0x007fdccd5498c0>:0x007fdcc04894d8>):

1 个答案:

答案 0 :(得分:2)

您可以通过将局部变量传递给部分来实现此目的,如下所示:

<%= render partial: 'achievements/new_certification', locals: {ff: ff} %> # not a fan of the naming

然后在 achievement / _new_certification.html.erb

<div class="field">
  <%= ff.label :certification_name, 'Cert Name' %>
  <%= ff.text_field :certification_name %>       
</div>

Documentation on partials