Rails Nested Routes
Nested Routes…”Oh, the Joy!”
What is a Nested Route?
One way to think about a “Nested Route” is through the has_many :through association. This is used to set up a many-to-many connection with another model. A resource that is considered logically children of other resources.
class Userhas_many :drink_ordershas_many :drinks, through: :drink_ordersendclass Drinkhas_many :drink_ordershas_many :users, through: :drink_ordersendclass DrinkOrderbelongs_to :userbelongs_to :drinkend
The point of having nested routes/resources is to help DRY (“Don't repeat yourself”) up our code, this will also keep our routes neat and pretty. Readability is super important a nested resource URL can convey that one resource belongs to another one. This can make debugging easier.
Beware of potentially long urls and how you name your models.
i.e : current_user_drinks_order_drinks_path or :edit_drink_drink_order_path
It’s really easy to get confused with these names. I have in the end realized it would have been easier to simply call it “orders” instead of “drink_orders”. Having many relationships between the resources the nested approach can lead to rather long and complicated URLs.
I heard that is best to go two depths sometimes three say if our IDs are short and easily readable.
Are We in Nested or Not?!
So, often I find myself confused. Where am I? Where am I going? What am I doing? If you want to know whether or not you’re in your nested route. If you look at the below code, you will see that I have @drink assigned inside class DrinkOrder. By assigning it to Drink(class)with the find_by_id (method we get from Active Record) we are able to take in the params[:drink_id] which is the foreign key. Since we are taking in the foreign key in params, we are there for in the nested route.
class DrinkOrder private def set_drink @drink = Drink.find_by_id(params[:drink_id]) end
What to Remember!
The purpose of using Nested Resources is to simplify our lives with the work we do. We are able to improve the readability and turn our developer experience into a pleasant one. It is necessary to utilize Nested Resources because there will be instances where our data-source will not give us a way to identify a nested resource solely by their ID. It’s a…
love hateRelationship!Happy Coding! From your,