Routes are a very confusing topic that have taken me a while to understand and trying to understand rails without understanding routes looks kind of like this…
The basic concept is that rails routes are how rails apps read a URL. When a user goes to a certain URL, the URL is sent to the rails routes folder (located in config/routes.rb). If the routes folder recognizes the URL, it then looks inside it’s corresponding controller for actions (or methods) that match that URL. Basically, it’s a way to redirect incoming requests to controllers and actions within the app.
Resourceful Routes
Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, a resourceful route declares them in a single line of code.
resources :photo
creates the following information…
Tip - you can also add multiple resources in a single line:
resources :photo, :magazine, :animal
You can think of the controller/action part of the routes as a direction. “photo#index” tells your app to go to the photo controller and the index action and look for further instructions there.
If you don’t want the user to have access to all 7 routes that are created when using resources, rails provides the “only” keyword so you can specify exactly what you want to be created.
resources :photo, :only => [:index, :show]
This will only create the photo#index and photo#show.
Non-Resourceful Routes
If you wish to create routes that do not fit the 7 routes that are created with resources, you can make custom routes with the HTTP helper methods. These include GET, POST, PATCH, PUT and DELETE. An example of this is below
GET "/photo", to: photo#new'
GET photo/:id' => photos#show'
You can even make your routes respond to more than one HTTP helper method using :via and :match.
match photo/:id' => photos#show', via: [:get, :post]
If you would like to change the URL of your custom route you can do so with the as keyword…
Now that I have a better understanding of routes, I can hopefully master rails as well as this dog has mastered catch!
Don’t forget you can always see all your routes by typing in “rails routes” into your terminal or going to localhost:3000/rails/info/routes
For a more comprehensive overview of Rails Routes checkout the Rails Guides!!!!