“Don’t forget the Routes!” Making your MVC in a Rails project

Photo by Juan Rojas on Unsplash

So, we’re finally learning about Ruby-on-Rails in this new module and I am loving it compared to my Sinatra project (lowkey got PTSD from it, LOL). Whilst building out my Rails project, I had noticed many similarities, especially when it comes to the body of the project that’s centered around Models, Controllers, & Views. However, out of all the similarities that exist between Rails and Sinatra, one major difference remains….

What do we do about the “routes”?

Well, first off, what are our routes anyway?

Routes are used in Rails sort of like how we have our environment in Sinatra. They let us render and redirect the user to various pages via “paths” by calling on the controllers in the project and link them to different HTTP requests. This helps us generate URLs without having to hard-code them as strings.

The formatting of the “routes.rb” file comes with a line that allows you to start mapping out your paths that will directly correlate with your MVC. In a routes.rb file, you may find any of these five types of routes:

  • RESTful Routes
  • Named Routes
  • Nested Routes
  • Regular Routes
  • Default Routes

The routes that I had used in my rails project specifically were nested routes. Nested Routes are routes that let you declare that one resource is contained within another resource. For example, my project had to do with makeup and makeup bags to be able to store the makeup in. Each user has access to their own bags, but is able to add makeup products or tools to their makeup bag if they so choose. Due to that, it made sense for me to use nested routes in my application because all of my models are linked to each other.

RESTful routes is also another standard way of drawing out routes in a Rails application. a RESTful route maps between HTTP verbs, controller actions, and (implicitly) CRUD in a database. By creating a single entry in the routes file in your application, Rails can draw out multiple routes that can interact directly with your database.

One of the major things that I learned (the hard way LOL) about routes whilst building out my application: your action ALWAYS has to match the route that you’re calling on. If it doesn’t you’ll always encounter errors within the flow of your application. Routes are ultimately set to make rendering and redirection easier in the application as a whole.

A black girl, making her own way in the tech space