Implementing Nested Attributes in Ruby on Rails
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:
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:
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.
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:
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.