Understanding Ruby on Rails Explicit Routes and Creating Custom Routes

Zermina Ejaz
3 min readSep 9, 2019

--

Ruby on Rails Explicit Routes

“Ruby on Rails, or Rails, is a server-side web application framework written in Ruby under the MIT License. Rails is a model–view–controller framework, providing default structures for a database, a web service, and web pages”

Rails is AMAZING. It literally takes care of all the work for us, so we can focus on building custom features for our application and not have to spend too much time on the standard pages every application has.

Using Lines 2–4 are great, but you should really know how Rails is performing its magic! SHAZAM

The code on LINE 2: “resources :sweaters”—is a resourceful route that exposes a number of helpers to the controllers in your application. The Sweaters Index, Show, New, Create, New, Edit, Update, Destroy routes are all taken care of for you!

This is extremely helpful, but you should not rely on this resourceful route alone. You will want to create custom routes when you add unique features to your application.

Let’s take a closer look at Line 5.

Break this line up into three parts

  1. get ‘/grandmas’
  2. to: ‘grandmas#index’
  3. as: ‘grandmas’

Part 1 will be the url the user will enter into our browser and send a get request to.

Part 2 also has two parts to it ‘grandmas’ and ‘#index’. The name before the # sign is the name of the controller it will go to. ‘#index’ means it will look for the index method in the grandmas controller. It finds the method called index, perform the actions in that method and then look in the views folder that has the name of the controller, grandmas, and then look for a file with the same name as the method, index.html.erb. This is how Rails knows where to go, and what to perform.

Part 3 is the prefix, or the nickname you would like to call this route.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — -

Now that you understand Line 5, you can create custom routes, just follow the steps and the naming convention to make things easier for you!

LETS GO!

Go into your Routes file.

Type out your route.

> get ‘/path’, to: “controller_name#method_name”

Go into your controller (diaries_controller) and type out your method with the name given (EX. diary_entries)

Lastly, create a View under the appropriate Folder.

Since we are in the “Diaries” controller, go into Views > Diaries and then create a file with the same name as the method we created in the controller.

And TADAAAA, You’re DONE!

--

--