This is a Rails gem for conveniently manage multiple nested models in a single form. It does so in an unobtrusive way through jQuery or Prototype.
This gem only works with Rails 3. See the rails2 branch for a plugin to work in Rails 2.
Add it to your Gemfile then run bundle to install it.
rails g nested_form:install
Use the nested_form_for helper method to enable the nesting.
<%= nested_form_for @project do |f| %>
You will then be able to use link_to_add and link_to_remove helper methods on the form builder in combination with fields_for to dynamically add/remove nested records.
<%= f.fields_for :tasks do |task_form| %> <%= task_form.text_field :name %> <%= task_form.link_to_remove "Remove this task" %> <% end %> <p><%= f.link_to_add "Add a task", :tasks %></p>
It is often desirable to move the nested fields into a partial to keep things organized. If you don't supply a block to fields_for it will look for a partial and use that.
<%= f.fields_for :tasks %>
In this case it will look for a partial called “task_fields” and pass the form builder as an f variable to it.
If you are using jQuery, nested:fieldAdded<tt> and <tt>nested:fieldRemoved events are triggered on the form element after adding and removing fields.
This gem was originally based on the solution by Tim Riley in his complex-form-examples fork.
Andrea also wrote a great blog post on the internal workings of this gem.