Rails Routes P.1 Understanding Route Structure

One of the most confusing things I found whilst learning Rails was how to correctly use routes. It is my hope through this blog I can uncover some of the magic our routes.rb facilitates.

To list the existing routes in your project simply run

rails routes

When running this command your terminal will provide output similar to the screenshot below. You can refine your search to specific model names using a pipe, for example..

rails routes | grep blog

This will refine our search to only show routes linked with the blog model, this is particularly useful when working with larger applications.

Note: depending on your version of Rails and configuration these collum’s may be ordered differently, however they will contain the information that follows.

Ok so let's cover what these routes actually do!

Collum one (left)

On the left we see a model followed by a hash, then a controller action, simply put this route handles this model followed by this action. For example…

blog#show = This route shows the entries in the blog model

blog#destroy= This route deletes items entries in the blog model

Typically CRUD actions are routed in this way, but there's more! You can refine routes in this folder to link to your own methods, for example, if I wanted to make a method called do_something for a blog I could route it as follows…

blog#do_something

Collum two ( left middle)

Here we see a prefix for each method in our application, for example, if we had an edit method in a controller for a model named blog we may have the prefix edit_blog.

These prefixes are particularly useful in conjunction with Rails helper methods. In a sense, a prefix is a shortcut. For example, say with have the prefix new_blog, we could combine it with a Rails helper such as _path (new_blog_path).

Collum Three ( right middle)

The next collum over, you will see a number of HTTP methods, the Rails routes require these methods in order to understand what kind of request they need to make.

POST (Create something and add it to the database)

GET (Read/retrieve something from the database)

DELETE (delete/destroy something in the database)

PATCH (Update/Replace something in the database)

PUT (Update/modify something in the database)

Collum Four ( right )

In this collum, we see the URI (Uniform Resource Identifier) pattern, which in short is the URL of our route path.

For example, a URI/URL would look something like…

blogs/:id(.:format) = hostname/blogs/02

Hi, I’m Steven, most call me Steve! I’m a programmer, musician, and artist. This blog contains various tutorials and posts related to 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