How to use Nested Attributes in Rails 3 Forms

rails image21
Social sharing

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? }
end
  •    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.new
@employee.addresses << Address.new
end

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

Your recently viewed posts:

Jayadev Das - Post Author

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 ‘About 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!

    Contact Us

    We’d love to help & work with you




    When do you want to start ?


    Enter your email address to stay up to date with the latest news.
    Holler Box

    Orange Exit pop up

    Subscribe for the latest
    trends in web and
    mobile app development
    Holler Box

    Exit pop up

    Sad to see you leaving early...

    From "Aha" to "Oh shit" we are sharing everything on our journey.
    Enter your email address to stay up to date with the latest news.
    Holler Box