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