Ruby on Rails Nested Form Fields

Ruby on Rails Nested Form Fields

It’s super common to want to edit records along with their has_many associations on a single page.

This Rails gem helps creating forms for models with nested has_many associations and relies on jQuery to dynamically add and remove nested form fields without a page reload.
- Works for arbitrarily deeply nested associations (tested up to 4 levels).
- Works with form builders like simple_form.
- Requires at least Ruby 1.9 and the Rails asset pipeline.

To install, add nested_form_fields to your application’s Gemfile:

Gemfile
1
gem 'nested_form_fields'

Run bundle intall to install the gem:

1
bundle install

In application.js file add:

application.js
1
//= require nested_form_fields

assuming that you have a User model with nested videos:

user.rb
1
2
3
4
class User < ActiveRecord::Base
  has_many :videos
  accepts_nested_attributes_for :videos, allow_destroy: true
end

Use the nested_fields_for helper inside your user form to add the video fields:

1
2
3
= form_for @user do |f|
  = f.nested_fields_for :videos do |ff|
    = ff.text_field :video_title

Links to add and remove fields can be added using the add_nested_fields_link and remove_nested_fields_link helpers:

1
2
3
4
5
= form_for @user do |f|
  = f.nested_fields_for :videos do |ff|
    = ff.remove_nested_fields_link
    = ff.text_field :video_title
  = f.add_nested_fields_link :videos

Note that remove_nested_fields_link needs to be called within the nested_fields_for call and add_nested_fields_link outside of it via the parent builder.

So far so good, That’s it!!! See ya!!! :)