Creating Nested Routes and Resources for Ruby on Rails

Benjamin Cheng
2 min readApr 24, 2021

The Ruby on Rails framework is designed to make web development simple and intuitive. The model-view-controller (MVC) architectural pattern for Rails is widely adopted and used as a way to separate the application’s logic, the routing, and the way the data is presented to the user and how they interact with it. Along with MVC design, creating resources, CRUD operations, and nesting resources are easy as pie with using Ruby on Rails.

A lot of the routing is simplified with Ruby especially as we get into more complex routing systems such as nested routes. Routing is a technique in which the application redirects incoming traffic to the correct controllers and handlers. For RoR projects, most of the routing is created in config/routes.rb.

Resources are another way of routing in that it is expected to take in CRUD operations when users refer to it. Resources automatically create the most basic routes for the application. For example, a Post resource would be linked to a posts table in the database. A controller would be mapped to it, post_controller.rb. With this set, routes such as posts#index, posts#new, posts#create, etc would be generated. With just a simple command most of your basic functionalities are up and ready to use.

Now for resting resources. This generally involves relations between models, mostly one model nesting the other. Nesting refers to belongs_to and has_many between two models. For this instance, the Posts model can have many Comments. Other examples in which there can be a many-to-many relationship can be implemented through has_many :through association and with join tables.

Setting up a nested resource according to our example models of Posts and Comments. The comment should be nested in the parent post model in routes.rb as seen below:

Rails.application.routes.draw do 
resources: posts do
resources: comments
end
end

In addition to that, the model has to have relations with each other. The post model should be similar to the below code:

class Post < ActiveRecord::Base
has_many :comments
end

And the comment model should belong to posts.

class Comment < ApplicationRecord
belongs_to :post
end

With these relationships and nest routes set up, we are able to reference all of the comments for a post in our index for instance:

def index
@comments = @post.comments
end

Additionally, you can also update the new method to associate each new comment with a post each time.

def new
@comment = @post.comments.build
end

These are just simple nested routing and resources. As an application scales up, the complexity multiples however Ruby on Rails framework lets you easily do that as well.

--

--