[Solved] Rails: Form fields & Loops


Rails has a built in mechanism for handling nested forms.

Lets say you have:

class Company < ActiveRecord::Base
  has_many :brands
  accepts_nested_attributes_for :brands
end

class Brand < ActiveRecord::Base
  belongs_to :company
end

class CompaniesController < ApplicationController
  def new
    @company = Company.new
    @company.brands.new # seeds the form with a new record for brands
  end

  def edit
    @company = Company.find(params[:id])
    @company.brands.new # seeds the form with a new record for brands
  end
end

Since Company accepts_nested_attributes_for :brands we can create a company and brands at the same time by passing params[:company][:brands_attributes]. Fortunately we don’t have to do this manually.

<%= form_for(@company) do |f| %>
  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>
  <fieldset>
    <legend>Brands</legend>
    <%= f.fields_for(:brands) do |brand_fields| %>
      <%= brand_fields.label :foo %>
      <%= brand_fields.text_field :foo %>
    <% end %>
  </fieldset>
<% end %>

This will use an array format for the name attributes:

<input name="company[brands_attributes][0][foo]" #...

2

solved Rails: Form fields & Loops