2.2 RCAV: Route
The key is routes. Routes are how we connect a URL to an action.
The config/routes.rb
It’s finally time to move out of our public/
and tasks/
folders, and use more of our Rails application by working in the app/
folder, where most of our code goes, and with this one file routes.rb
that is in the config/
folder. file included in every Rails app lists all of the URLs (routes) that a user can visit. When someone visits the URL we say which class and which method Rails should execute to handle the request. Here is an example of a route:
# config/routes.rb
self.get("/rock", { :controller => "application", :action => "play_rock" })
The method here is get
Later we’ll use other methods, like post
, if we want to support requests using the other HTTP verbs. and there are parentheses for its two arguments:
A
String
: the path that we want users to be able to visit (the path is the portion of the URL that comes after the domain name). Here it is"/rock"
.A
Hash
: this is where we tell Rails which method to call when a user visits the path in the first argument. (We’ll have to actually write this method in the next step, after we write the route.)
The Hash
must have two key/value pairs:
:controller
: The value for this key is what we’re going to name the Class that contains the method we want Rails to call when the user visits the path. For now we’re going to default this value to"application"
.:action
: The value for this key is what we’re going to name the method itself. Action is the term used to refer to Ruby methods that are triggered by users visiting URLs.
The Hash
is saying: “Use a Class
(controller) called application_controller
, and in that Class
use a method
(action) called play_rock
to generate a response for the user.”
Don’t be confused by the key names :controller
and :action
, these are equivalent to a Ruby Class and method. They just have special names in the lingo of web applications.
The get
method is inherited, we don’t need to build this method ourselves, which saves us a lot of time. We get the plumbing for free and we just need to tell Rails how we want each request to be handled by declaring our routes.