19
Forms can have...nests?
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.
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:
- Picking a doctor from an existing dropdown list OR
- 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.
- Proper associations
![](https://res.cloudinary.com/practicaldev/image/fetch/s--iZDXbnnd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r06l1egpilc4hbtjcrdc.png)
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
![](https://res.cloudinary.com/practicaldev/image/fetch/s--8ZZvoc2R--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k33834cmbscu55tiae17.png)
![](https://res.cloudinary.com/practicaldev/image/fetch/s--MRdJpLlh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzofwtwv93p27uauq0h3.png)
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
![](https://res.cloudinary.com/practicaldev/image/fetch/s--Tf7Anfe0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mbld5d572bu9bs4t3xfg.png)
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).
Nested forms are just another way for developers to add realistic functionality for users as they interact with our applications.