Nested Attributes with Nested Forms

Tram Ho

Introduce

Instead of just getting used to creating and updating a record of an object, we can now create and update child objects that are linked to each other. Nested Attributes allow you to save the properties of the object’s record through its parent object. By default, Nested Attributes is turned off so you need to add the model class #accepts_nested_attributes_for. For example:

Practice:

To get acquainted quickly with Nested Attributes, we try to create a simple small app

Create 2 models

run rails db:migrate

On the User model:

In UsersController

In views / users / _form.html.erb we use fields_for used in Nested Forms

So far, we have built a nested forms that can create a user object and link its address at the same time.

A little more advanced

The above is a basic guide to getting to know Nested Attributes and Nested forms. The downside of the above form is only a static form, we can not know in advance how many addresses the user wants to add, so now let’s try to create a dynamic form that allows the user to add an address with just one click.

Edit the form a little bit, add more classes and add js, css.

After the above step you will have a form like this. Now it has become a Dynamic form that allows you to create more addresses.

The next only need to fill in information and click submit to see the results.

Source:

Above are the basic steps to quickly familiarize yourself with Nested Attributes. In addition to more carefully can refer to below.
https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
http://jyrkis-blogs.blogspot.com/2014/06/adding-fields-on-fly-with-ruby-on-rails.html
https://www.tutorielsenfolie.com/en/tutorials-7-Dynamic-form-in-JavaScript.html

Share the news now

Source : Viblo