How to use Nested Attributes in Rails 3 Forms

How to use Nested Attributes in Rails 3 Forms

< 1 Minute Read

For example, say we want to add multiple addresses(attributes) having many fields inside a create/edit employee form

Step# 1

  •  Create a model named Employee
  •  Create another model named Address
  •  Add the following relationship in Employee model
class Employee < ActiveRecord::Base
has_many :addresses, :dependent => :destroy
accepts_nested_attributes_for :addresses, :reject_if => lambda { |a| a[:city].blank? }
  •  Nested attribute form rejects if the city field of the address is blank

Step# 2

  •  In Employees controller add the following in the “new” action
def new
@employee =
@employee.addresses <<

Step# 3

  •  In the view file add the following inside the form attribute
<%= form_for @employee, :html => { :multipart => true, :id => 'new-employee' } do |f|
<%= f.label :name, 'Name' %>
<%= f.text_field :name %>
<% end %>
Jayadev Das

Do what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘bout Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!