DEV Community

Cover image for Forms can have...nests?
Gia Jennings
Gia Jennings

Posted on • Updated on

Forms can have...nests?

What's the purpose of a nested form?

In Rails, forms allow a user to input information and persist or save that data to a table, in a database. This is great if the information in the form only pertains to one table or model. However, what if the user wants to save information to multiple tables within one form? Well, that's when nested forms come to the rescue.

How are nested forms built?

To better explain, we'll refer to my Rails application - CalenDOC (an app for users to track medical appointments with relevant information (i.e. appointment date & time, doctor, notes etc.)).

With my app, I wanted to grant users the ability to create an appointment with the choice of:

  1. Picking a doctor from an existing dropdown list OR
  2. Creating a new doctor

In order to offer this functionality, I needed to utilize a nested form that would persist the information as a new appointment object and the information for the new doctor object, if he or she decided to create a new one.

Nested Form Ingredients

  • Proper associations

Appointments Model

Since an appointment belongs to a doctor, it has access to the doctors_attributes key which gives us access to the the method illustrated above; accepts_nested_attributes_for :doctor.

  • f.fields_for

Appointment Form

Doctor Nested Form

Here, I utilized the f.fields_for line to include fields pertaining to the Doctor object even though this form is nested inside the Appointment form.

  • New Method - Appointment & Doctor

Appointments Controller

Lastly, we use the .build method within our new appointment so we can persists information about the new Appointment when the form is submitted, along with the new Doctor (if applicable).

Conclusion

Nested forms are just another way for developers to add realistic functionality for users as they interact with our applications.

Top comments (0)