Search code examples
ruby-on-railsformssimple-formnested-attributesfields-for

Rails: How to customise the order of fields in a form with nested fields


I have a form that saves attributes to two models Company and nested model Address in a single form using simple_nested_form_for and simple_fields_for.

The attributes:

Company:
-legal form
-uploads

Address:
-name
-website

In my form I wish to change the order of the fields

-name (Address model)
-legal form (Company model)
-website (Address model)
-uploads (Company model)

thus interchanging the form attributes and nested_field attributes

I tried the following, but that did not seem to work.

<%= simple_nested_form_for @company do |f| %>
    <%= f.simple_fields_for :address do |c| %>
        <%= c.input :name %> 
    <% end %>
    <%= f.input :legal_form %>
    <%= f.simple_fields_for :address do |c| %>
        <%= c.input :website %> 
    <% end %>
    <%= f.input :uploads %>
<% end %>

How do I make this work?


Solution

  • While it doesn't look like all your attributes line up ( you said uploads was address and website was in company in your attributes list but the form doesn't match that ) there is still a simple solution to your question.

    Nested fields rely on their builder to denote which part of the params hash to put them in. So simply call the builder that you need.

    <%= simple_nested_form_for @company do |f| %>
      <%= f.simple_fields_for :address do |c| %>
        <%= c.input :name %> 
        <%= f.input :legal_form %>
        <%= c.input :website %> 
        <%= f.input :uploads %>
      <% end %>
      <%= f.submit %>
    <% end %>
    

    In each place that you need the company fields, you'll call builder f and in each place you need the address fields, you'll call builder c - but nested them all inside the lowest common denominator so they're all available.