Nested Attributes: Ruby on Rails

Series of nesting dolls.
Series of nesting dolls.

Relationships can be very messy. Ideally they they are clean and make us happy, but rarely does that actually come to pass. Especially when you have a single table that acts as a lynchpin in your data structure, Rails has a solution for you: nested attributes. This relationship is remarkably easy to implement, once you know where to put the various pieces. So let’s get to unifying our tables with nested relationships!

First, we’ll need a project with two models. In this case we’ll go ahead and use Rails to get us up and running quickly. Once your file is started, go ahead and run the following in your project directory terminal:

Followed by:

This will build out a User with all of our routes, controller, and model, and a model for our Address. Next we’ll go into the model file for both of these, starting with User.

This sets up our User class to be able to do full CRUD with address. Next inside of Address model:

Now we just need to head over to users_controller.rb and finish up the last of the magic. With scaffold you should already have all your CRUD methods and strong params established, so now we’ll just add our relationship to the Address class. Anywhere where you are rendering back the json of User, add an includes for Address.

And finally under the private heading for our user_params we’ll need to allow address attributes.

At this point you can use a service like Postman to do full CRUD actions with only User calls. However, the includes sends the address key, not the address_attributes key. So the strong params will not allow the data back until that key has been mutated. The following code would work for a POST request, creating both a User and an associated address. (Formatted for Postman)

And this would work for an PATCH request:

And this would be the result of a GET request:

If you were hoping to unify your data using nested attributes I hope this helped set you on the path to functional code! This is a great way of keeping your data organized and could even help make less requests for data in the long run. While it does have some quirks, namely needing to add _attributes to your nested return keys, overall the implementation is not hard!

Written by

A creator to the core, he enjoys all games (especially collaborative ones), baking bread, and software development.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store