back to

The Rails 4 Way

ARCHIVED

Archived: This project has been archived. Cards can no longer be completed.

Routing

Alejo
Alejo completed this card.
The routing system in Rails is the system that examines the URL of an incoming request and determines what
action should be taken by the application. In other words, the routing system maps URLs to controller actions.

When you input a URL into the browser, rails goes through the routes.rb file to find a defined route that matched the URL. It starts searching at the top and stops until it finds something that matches. For example, this URL "http://localhost:3000/9" will match this route: 
get ":id" => "users#show"

The URL pattern string ("users/:id") is usually made up of a static string ("users") and a segment key (":id"). This means that any URL that matches this route will have to start with "users" and will contain a parameter that can then be used inside the controller action that the route calls.

An interesting thing is that the segment key [:id] is not magic, it acts just as a parameter passed to the controller action. So, we could define in our routes get "users/:blah" and then call from our controller "User.find(params[:blah])".

Another thing we can do, is constraint a route, for example as to accept only numerical values in the id. Then, establish a fallback for all non-numerical URLs that match the route. As seen here:
constrained route and fallback.png 67.34 KB