Skip to content

Create Nested Form in Rails 3.1



While we creating some forms, also need to create some additional forms. In rails can easily create those type of form using gem “nested_form”. It can  manage multiple nested models in a single form. To know more

can see how it works

i have two model name Project,task. Project has many task. i want to create multiple task when create a project.

include gem in Gemfile

gem "nested_form", :git => ''

then run command in  project directory

$ bundle install

This gem add new  nested model by using JavaScript. it automatically create JavaScript file.To create JavaScript run this command

$ rails g nested_form:install

now one file created in public/javascripts/nested_form.js

copy the nested_form.js  to app/assets/javascripts/

if your server is running restart to load new installation.

set controller and model like


class ProjectsController < ApplicationController
def index

def new

def create[:project])
flash[:notice] = "Successfully Created project."
redirect_to projects_path

def edit

def update
flash[:notice] = "Record Successfully updated"
redirect_to projects_path

def destroy
redirect_to projects_path


in project.rb

class Project < ActiveRecord::Base
has_many :tasks, :dependent => :destroy
attr_accessible :tasks_attributes,:name, :description
accepts_nested_attributes_for :tasks, :allow_destroy => true

validates :name, :presence => true

in task.rb

class Task < ActiveRecord::Base
belongs_to :project

in my views/projects/_form.html.erb

<%= nested_form_for @project do |f| %>

<%= f.label :name %>
<%= f.text_field(:name) %><br />
<%= f.label :description %>
<%= f.text_field(:description) %><br />
<h3> Tasks</h3>
<%= f.fields_for :tasks do |task| %>
<%= task.label :name %><br />
<%= task.text_field :name %><br />
<%= task.link_to_remove "Remove this task" %>
<% end %>
<p><%= f.link_to_add "Add a task", :tasks %></p>
<%= f.submit %>
<% end %>

f.fields_for :tasks render the partial file “task_fields” create  partial file name as _task_fields.html.erb in views/projects/

and include the nested fields.

while click “link_to_add’, “link_to_remove” it calls the addField removeField in nested_forms.js file.

Nested form fields are added via javascript.



From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: