简体   繁体   中英

Rails: split a nested form into partials

I have a nested form which works perfectly fine, however, I'm trying to figure out how to split that nested form into a partial.

original form:

  <%= 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' %> 

Here's what I'm trying to do....

  <%= 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' %>

here's the partial.

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

the problem is that it doesn't know what to do with the 'ff' variable.

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

You can achieve this by passing a local variable to your partial like so:

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

Then in achievements/_new_certification.html.erb

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

Documentation on partials

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM