Codementor Events

Implementing Nested Attributes in Ruby on Rails

Published Jan 08, 2022

Ruby on Rails (RoR) Nested attribute feature allows us to save attributes of a record through its parent. In this example, I will be applying the nested attribute to a car auction app where we have many auctions. Each auction will be associated with one photo (which will comprise of 4 images) and one my_solicitor (The legal personnel who will manage your car auction deal on the App) record.

Adding the Nested attribute to the Auction model

For us to add the nested attribute to the car auction moedel - to establish relationship between auction & photo as well as auction & my_solicitor - we need to make our aucion model looks like this:

Screenshot from 2022-01-08 13-07-12.png
In the code snippet above, we are establishing a one-to-one relationship between auction and photo, and one-to-one relationship between auction and my_solicitor. This means that each Car Auction will have only 1 solicitor and only 1 photo(max of four images) object.

Adding photo and my_solicitor model

The photo and my_solicitor models will look like this:
Screenshot from 2022-01-08 12-54-10.png

Screenshot from 2022-01-08 13-02-51.png

Implementing Auction Controller to accept the photo and my_solicitor data

We are going to use the photo_attributes as well as the my_solicitor_attributes key words to add the photo and my_solicitor params to the Auction params.

Screenshot from 2022-01-08 12-59-34.png

Modifying the Auction Form to accept the photo and my_solicitor data on creation and edit

We will take advantage of the fields_for method make our Auction form be able grab photo and my_solicitor data from the view. We will add this field for both the photo and my_solicitor association on the Auction form like this:
Screenshot from 2022-01-08 07-50-24.png

Screenshot from 2022-01-08 12-41-09.png

Conclusion

The main concept of Nested Attributes availed in this post is that we did not have to write separate controller code to handle the input and association of the photo and my_solicitor. We allowed the attributes to reach the model to avoid them being blocked by strong parameters by adding photo_attributes and my_solicitor_attributes to the auction_params in the AuctionsController.

Discover and read more posts from Oladayo
get started
post commentsBe the first to share your opinion
Show more replies