Chapter 2 - Routing Flashcards
The two Purposes of routing
- Recognizing incoming requests and mapping them to a corresponding controller action, along with any additional variable receptors
- Recognizing URL parameters in methods such as link_to and matching them up to a corresponding route so that proper HTML links can be generated
The two Purposes of routing
It maps requests to controller action methods, and it enables the dynamic generation of URLs for you for use as arguments to methods like link_to and redirect_to.
REST
representational state transfer (REST).
Regular Routes
get ‘products/: id’ = > ‘products# show’
Constraining Request Methods
As of Rails 4, it’s recommended to limit the HTTP method used to access a route. If you are using the match directive to define a route, you accomplish this by using the :via option:
match ‘products/: id’ = > ‘products# show’, via: :get
segment keys
The URL pattern string can contain parameters (denoted with a colon), referred to as segment keys. In the following route declaration, :id is a segment key:
get ‘products/: id’ = > ‘products# show’
Redirect method
get “/ foo”, to: redirect(‘/ bar’)
Route Globbing
In some situations, you might want to grab one or more components of a route without having to match them one by one to specific positional parameters.
You define it by globbing the route with an asterisk.
get ‘items/ list/* specs’, controller: ‘items’, action: ‘list’
Create Named Route
get ‘help’ = > ‘help# index’, as: ‘help’
In this example, Rails will generate methods called help_url and help_path in controller and view contexts, which you can use wherever Rails expects a URL or URL components:
link_to “Help”, help_path
And, of course, the usual recognition and generation rules are in effect. The pattern string consists of just the static string component “help”. Therefore, the path you’ll see in the hyperlink will be the following:
/help
Create Named Route
get ‘help’ = > ‘help# index’, as: ‘help’
In this example, Rails will generate methods called help_url and help_path in controller and view contexts, which you can use wherever Rails expects a URL or URL components:
link_to “Help”, help_path
And, of course, the usual recognition and generation rules are in effect. The pattern string consists of just the static string component “help”. Therefore, the path you’ll see in the hyperlink will be the following:
/help
name_path vs name_url
> > app.clients_path = > “/ clients”
> > app.clients_url = > “http:// www.example.com/ clients”
Namespaces
namespace :auctions, :controller = > :auctions do get 'new' = > :new get 'edit/: id' = > :edit post 'pause/: id' = > :pause end