Search code examples
ruby-on-railsformsnested-attributesfields-for

Rails - How to split nested attributes through the form?


I understand we can use fields_for to create a subsection of fields for nested attributes. However, I would like to split them through the form. How can I do this?

For instance:

Suppose I have a model foo with a nested bar model, like this:

    class Foo < ApplicationRecord
      has_many :bars
      accepts_nested_attributes_for :bars
    end

A general view would be something like this:

    <%= form_for @foo do |f| %>
      <!-- foo fields -->

      <%= f.fields_for :bars do |f_bar| %>
        <!-- bar fields -->
      <% end %>

      <%= f.submit "Submit" %>
    <% end %>

But for aesthetics reasons, I don't want all the bars agglomerated at one place. I would like to do something like:

    <%= form_for @foo do |f| %>
      <!-- foo fields -->

      <%= f.fields_for :bars do |f_bar| %>
        <!-- bar fields of one bar -->
      <% end %>

      <!-- other foo fields -->

      <%= f.fields_for :bars do |f_bar| %>
        <!-- bar fields of another bar -->
      <% end %>

      <!-- The previous repeats many more times in a non predictable way -->

      <%= f.submit "Submit" %>
    <% end %>

So it would be perfect for me if I didn't have to show all the bars at once. Somebody knows how to that?


Solution

  • So, it happens that all I needed was make fields_for show only one instance per time.

    I discovered that fields_for lets you specify a particular object to render the fields. So, I just created a counter and added one @foo.bars[counter] per time and it magically worked, it was something like this :

        <% counter = 0 %>
        <%= form_for @foo do |f| %>
    
          <!-- foo fields -->
        
          <%= f.fields_for :bars, @foo.bars[counter] do |f_bar| %>
            <!-- bar fields of one bar -->
          <% end %>
          <% counter+=1 %>
        
          <!-- other foo fields -->
        
          <%= f.fields_for :bars, @foo.bars[counter] do |f_bar| %>
            <!-- bar fields of another bar -->
          <% end %>
          <% counter+=1 %>
        
          <!-- The previous repeats many more times in a non predictable way -->
        
          <%= f.submit "Submit" %>
        <% end %>