Flatiron Ruby on Rails — Project #3

Woot! I have almost made it through my 3rd phase with Flatiron School! I became a stay-at-home mom since the pandemic started so balancing school, housework, and being a mom has its’ challenges. Luckily, my child is very independent, and I can work on the course during the day.

I was super excited to start this project. For me, the material in this phase “clicked” quite a bit easier than the other 2 phases. Though the project was fun to complete, it threw me for some challenges as well.

For this project, I decided to create an application where a user can signup and write a letter to Santa. The user can create an elf to help send the letter to Santa. Think “Elf on the Shelf”.

One of my biggest hurdles for this Rails project was figuring out my nested routes. I wanted my user to be able to create a ‘letter’ to Santa which was nested under a specific elf, or they could create an elf and a letter at the same time.

Nested routes are routes that allow you to show the relationship between two objects. For my nested routes, I started with my relationship in my models. In order to have nested routes, there must be a has-many/belongs-to relationship established.

an Elf has_many :letters
Letters belongs_to an :elf

After that, I set up my nested routes

shallow: true builds nested index, new, and create routes for letters and all of the other CRUD routes unnested.

I ultimately refactored my letters controller to conditionally render based on the route. If the user is under a nested route, it will not render the form to create a new elf, but only the the form to send a letter that is associated with a specific elf.

In addition, if a user is not visiting a nested route, there will be a nested form to create a letter and an elf at the same time.

I decided to set my controller this way because it made the most sense to me.

In the new route, a user shouldn’t be able to create an elf while already nested under another elf. The route checks for an instance variable and if there isn’t one, it create a blank object. “.build” will tell associated objects about each other. Add elf_id to letters and it’ll add the letter to the elf’s letters collection. I used .build instead of .create because .create doesn’t worry about associations.

I refactored a conditional from my view into a helper method. If there is an elf object, then it will explicitly give the value, or if there is not an elf object, a form to create an elf will be rendered.

I had a lot of fun with this project! I can’t wait to continue my software engineering journey with Flatiron School!

--

--

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