Nested Fields
An engine designed for generic, dynamic nested forms which may be N>=1 levels deep.
Popular existing solutions for dynamic nested forms in Rails are implemented with javascript rather through controllers, probably because FormBuilders cannot be passed as params.
It relies on some parsing behavior within Rails which may be subject to change.
It handles both has_many
and has_one
relationships. For has_one
, it will allow 0..1 nested associates.
Requirements
Rails 3, jQuery
Styling
nested_fields
is not opinionated with regard to markup. Users are encouraged to provide their own styles.
Install
Add nested_fields
to the Gemfile and bundle install. The engine’s path provides the necessary javascript.
Associations
has_many
Each nested has_many
association will be bounded by a fieldset
with a link to add. Each of its associates will have a link to remove.
has_one
Each nested has_one
association will be bounded by a fieldset
with a checkbox for toggling the presence of an associate.
Usage
Include ‘nested_fields.js’ in the layout for the Add and Remove behaviors.
Declare accepts_nested_attributes_for each association. At present, nested_fields assumes that :allow_destroy is true.
Use the nested_fields_for helper method.
<%= nested_fields_for form_builder, :pluralized_association_name %>
For example, where f is a the builder for an object which has_many
:associates
<%= nested_fields_for f, :associates %>
The same type of the form builder argument (e.g. Formtastic, SimpleForm, etc.) will automatically be used for the nested fields.
Options
An optional block can be passed which will be displayed as a header.
<% nested_fields_for f, :associates do %>
...
<% end %>
:nested_partial
By default, nested_fields will look for a partial in app/views/associates/_fields.html.erb. This can be overridden with the :nested_partial option.
<%= nested_fields_for f, :associates, :nested_partial => 'path_to/partial.html.erb' %>
:legend
By default, nested_fields will provide a fieldset
legend
with the pluralized, titleized name of the associate class. This can be overriden with the :legend option.
<%= nested_fields_for f, :associates, :legend => 'My Title' %>
:positioned_by
The :positioned_by
option takes in the name of a field which is used for positioning (e.g. acts_as_list). It will cause the association’s fieldset
to have the .positioned
class and a data-positioned-by
attribute with the value.
A javascript function is provided which sets the values of existing (non-removed) inputs which have id’s ending in the value in the order they are displayed.
repositionNestedFields(nested_fieldset, position_field)
Triggers
The nested_fields_changed
custom event is fired by a nested associate’s div after being dynamically added/removed.
Example
Access demonstration code.
Credits
Inspired by Ryan Bates’ nested_form which itself is based on Tim Riley’s solution.