/ rails

Nested Forms

Feature is used when you need to save your nested model with the parent model.

Use-Case:
Suppose you have a model say Person and it can be associated with N number of Contacts. Using nested form we can associate 1..n contacts to the person.

Approach:
For associating a contact to a person, we need to build the contact model with respect to the person model. For has_many relation, @contact = @person.contacts.build and if has_one relation @contact = @person.build_contact.

Now we can use the @contact in the view, for this we use fields_for tag. And if we use simple_form then we use:

  = simple\_form\_for @person do |f|
    = f.input :name
    = f.simple_fields_for :contact do |c|
      = c.input :phone

Now we need to make Person model accept addition/changes for the Contact model. This is done by adding this line to Person Model:

accepts_nested_attributes_for :contacts

Also, attr_accessible :contacts_attributes

This is a basic functioning of the nested form.

Advance Features:

  1. If we need to reject Contact creation if the phone number isn't provided,
    :reject_if => proc { |a| a['phone'].blank? } # so we dont create empty contact alongside a person.

  2. For validating the child model alongside Person, we would have to use inverse_of in the relationship.

  3. If we need to add dynamic contact to the person, we can do it by jquery, cloning the fields_for view and adding it to the form with a unique key. You can check the entire implementation explained by Ryan Bates. But to avoid overhead one can use the [Cocoon(Cocoon)][1] Gem which is extremely easy to integrate and has good README and example applications with simple_form, formtastic, etc.

Thanks let me know if any issues or queries.
[1]: https://github.com/nathanvda/cocoon