Routing in a Rails Application

Kevin Kawai
Jul 30, 2017 · 2 min read

I recently started a new rails application and had some difficulty with setting up my routes the way I wanted. After a little bit of tinkering I managed to get them fixed and understood routes a little bit better so I though I would shared what I had learned.

#Index vs. #New vs. #Show

When I first started the application I wanted to create a page that would show all the contents of a database. Knowing what I wanted to do I typed into the routes.rb file

resources :routines, only: [:show]

When I went to the routes table in the console I was confused at seeing that the URL required an ID (something like /routines/:id). I knew that this was the “front” for all the routines in my database so there wouldn’t be an id. In my head I knew I wanted the URL to show something like /routines. I then realized that the “:show” portion was to show individual routines not all of them at once. For this I needed “:index”. Thus I changed the route to reflect what I needed.

resources :routines, only: [:index]

Now when you want to add functionality for creating a new entry in a database you actually need to create two routes. This is because you need a page to input the data and a route to send that data (this isn’t 100% and you could have the form for data entry somewhere else and have it POST to the create action). Typically the create route will reroute the user to another page and thus doesn’t necessarily require a view.

resources :routines, only: [:create,:new]

Lastly, instead of individually stating which routes and actions you want you can get all the necessarily URLs and action commonly used for a CRUD app by omitting only:

resources :routines

This would create a path for #index, #new, #create, #show, #edit, #update and #destroy.

For more information please refer to the rails routing documentation
http://guides.rubyonrails.org/routing.html

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade