aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/routing.md
diff options
context:
space:
mode:
authorPrem Sichanugrist <s@sikachu.com>2012-09-01 17:25:58 -0400
committerPrem Sichanugrist <s@sikac.hu>2012-09-17 15:54:22 -0400
commit872b7af337196febc516cb6218ae3d07f01a11a8 (patch)
treebc31fdc0803fff3aed26b6599cf2df7789055a41 /guides/source/routing.md
parent7bc1ca351523949f6b4ce96018e95e61cbc7719e (diff)
downloadrails-872b7af337196febc516cb6218ae3d07f01a11a8.tar.gz
rails-872b7af337196febc516cb6218ae3d07f01a11a8.tar.bz2
rails-872b7af337196febc516cb6218ae3d07f01a11a8.zip
Convert heading tags and heading section
Diffstat (limited to 'guides/source/routing.md')
-rw-r--r--guides/source/routing.md110
1 files changed, 58 insertions, 52 deletions
diff --git a/guides/source/routing.md b/guides/source/routing.md
index 8830401d7f..509101b3d6 100644
--- a/guides/source/routing.md
+++ b/guides/source/routing.md
@@ -1,4 +1,5 @@
-h2. Rails Routing from the Outside In
+Rails Routing from the Outside In
+=================================
This guide covers the user-facing features of Rails routing. By referring to this guide, you will be able to:
@@ -8,13 +9,14 @@ This guide covers the user-facing features of Rails routing. By referring to thi
* Automatically create paths and URLs using route helpers
* Use advanced techniques such as constraints and Rack endpoints
-endprologue.
+--------------------------------------------------------------------------------
-h3. The Purpose of the Rails Router
+The Purpose of the Rails Router
+-------------------------------
The Rails router recognizes URLs and dispatches them to a controller's action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.
-h4. Connecting URLs to Code
+### Connecting URLs to Code
When your Rails application receives an incoming request
@@ -30,7 +32,7 @@ get "/patients/:id" => "patients#show"
the request is dispatched to the +patients+ controller's +show+ action with <tt>{ :id => "17" }</tt> in +params+.
-h4. Generating Paths and URLs from Code
+### Generating Paths and URLs from Code
You can also generate paths and URLs. If the route above is modified to be
@@ -50,11 +52,12 @@ If your application contains this code:
The router will generate the path +/patients/17+. This reduces the brittleness of your view and makes your code easier to understand. Note that the id does not need to be specified in the route helper.
-h3. Resource Routing: the Rails Default
+Resource Routing: the Rails Default
+-----------------------------------
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.
-h4. Resources on the Web
+### Resources on the Web
Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as +GET+, +POST+, +PATCH+, +PUT+ and +DELETE+. Each method is a request to perform an operation on the resource. A resource route maps a number of related requests to actions in a single controller.
@@ -72,7 +75,7 @@ resources :photos
Rails would dispatch that request to the +destroy+ method on the +photos+ controller with <tt>{ :id => "17" }</tt> in +params+.
-h4. CRUD, Verbs, and Actions
+### CRUD, Verbs, and Actions
In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to particular CRUD operations in a database. A single entry in the routing file, such as
@@ -93,7 +96,7 @@ creates seven different routes in your application, all mapping to the +Photos+
NOTE: Rails routes are matched in the order they are specified, so if you have a +resources :photos+ above a +get 'photos/poll'+ the +show+ action's route for the +resources+ line will be matched before the +get+ line. To fix this, move the +get+ line *above* the +resources+ line so that it is matched first.
-h4. Paths and URLs
+### Paths and URLs
Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of +resources :photos+:
@@ -106,7 +109,7 @@ Each of these helpers has a corresponding +_url+ helper (such as +photos_url+) w
NOTE: Because the router uses the HTTP verb and URL to match inbound requests, four URLs map to seven different actions.
-h4. Defining Multiple Resources at the Same Time
+### Defining Multiple Resources at the Same Time
If you need to create routes for more than one resource, you can save a bit of typing by defining them all with a single call to +resources+:
@@ -122,7 +125,7 @@ resources :books
resources :videos
```
-h4. Singular Resources
+### Singular Resources
Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like +/profile+ to always show the profile of the currently logged in user. In this case, you can use a singular resource to map +/profile+ (rather than +/profile/:id+) to the +show+ action.
@@ -156,7 +159,7 @@ A singular resourceful route generates these helpers:
As with plural resources, the same helpers ending in +_url+ will also include the host, port and path prefix.
-h4. Controller Namespaces and Routing
+### Controller Namespaces and Routing
You may wish to organize groups of controllers under a namespace. Most commonly, you might group a number of administrative controllers under an +Admin::+ namespace. You would place these controllers under the +app/controllers/admin+ directory, and you can group them together in your router:
@@ -216,7 +219,7 @@ In each of these cases, the named routes remain the same as if you did not use +
|PATCH/PUT |/admin/posts/:id |update | post_path(:id) |
|DELETE |/admin/posts/:id |destroy | post_path(:id) |
-h4. Nested Resources
+### Nested Resources
It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
@@ -251,7 +254,7 @@ In addition to the routes for magazines, this declaration will also route ads to
This will also create routing helpers such as +magazine_ads_url+ and +edit_magazine_ad_path+. These helpers take an instance of Magazine as the first parameter (+magazine_ads_url(@magazine)+).
-h5. Limits to Nesting
+#### Limits to Nesting
You can nest resources within other nested resources if you like. For example:
@@ -273,7 +276,7 @@ The corresponding route helper would be +publisher_magazine_photo_url+, requirin
TIP: _Resources should never be nested more than 1 level deep._
-h4. Routing concerns
+### Routing concerns
Routing Concerns allows you to declare common routes that can be reused inside others resources and routes.
@@ -303,7 +306,7 @@ namespace :posts do
end
```
-h4. Creating Paths and URLs From Objects
+### Creating Paths and URLs From Objects
In addition to using the routing helpers, Rails can also create paths and URLs from an array of parameters. For example, suppose you have this set of routes:
@@ -345,11 +348,11 @@ For other actions, you just need to insert the action name as the first element
This allows you to treat instances of your models as URLs, and is a key advantage to using the resourceful style.
-h4. Adding More RESTful Actions
+### Adding More RESTful Actions
You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional routes that apply to the collection or individual members of the collection.
-h5. Adding Member Routes
+#### Adding Member Routes
To add a member route, just add a +member+ block into the resource block:
@@ -371,7 +374,7 @@ resources :photos do
end
```
-h5. Adding Collection Routes
+#### Adding Collection Routes
To add a route to the collection:
@@ -393,11 +396,12 @@ resources :photos do
end
```
-h5. A Note of Caution
+#### A Note of Caution
If you find yourself adding many extra actions to a resourceful route, it's time to stop and ask yourself whether you're disguising the presence of another resource.
-h3. Non-Resourceful Routes
+Non-Resourceful Routes
+----------------------
In addition to resource routing, Rails has powerful support for routing arbitrary URLs to actions. Here, you don't get groups of routes automatically generated by resourceful routing. Instead, you set up each route within your application separately.
@@ -405,7 +409,7 @@ While you should usually use resourceful routing, there are still many places wh
In particular, simple routing makes it very easy to map legacy URLs to new Rails actions.
-h4. Bound Parameters
+### Bound Parameters
When you set up a regular route, you supply a series of symbols that Rails maps to parts of an incoming HTTP request. Two of these symbols are special: +:controller+ maps to the name of a controller in your application, and +:action+ maps to the name of an action within that controller. For example, consider one of the default Rails routes:
@@ -415,7 +419,7 @@ get ':controller(/:action(/:id))'
If an incoming request of +/photos/show/1+ is processed by this route (because it hasn't matched any previous route in the file), then the result will be to invoke the +show+ action of the +PhotosController+, and to make the final parameter +"1"+ available as +params[:id]+. This route will also route the incoming request of +/photos+ to +PhotosController#index+, since +:action+ and +:id+ are optional parameters, denoted by parentheses.
-h4. Dynamic Segments
+### Dynamic Segments
You can set up as many dynamic segments within a regular route as you like. Anything other than +:controller+ or +:action+ will be available to the action as part of +params+. If you set up this route:
@@ -433,7 +437,7 @@ get ':controller(/:action(/:id))', :controller => /admin\/[^\/]+/
TIP: By default dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment, add a constraint that overrides this – for example, +:id+ => /[^\/]+/ allows anything except a slash.
-h4. Static Segments
+### Static Segments
You can specify static segments when creating a route:
@@ -443,7 +447,7 @@ get ':controller/:action/:id/with_user/:user_id'
This route would respond to paths such as +/photos/show/1/with_user/2+. In this case, +params+ would be <tt>{ :controller => "photos", :action => "show", :id => "1", :user_id => "2" }</tt>.
-h4. The Query String
+### The Query String
The +params+ will also include any parameters from the query string. For example, with this route:
@@ -453,7 +457,7 @@ get ':controller/:action/:id'
An incoming path of +/photos/show/1?user_id=2+ will be dispatched to the +show+ action of the +Photos+ controller. +params+ will be <tt>{ :controller => "photos", :action => "show", :id => "1", :user_id => "2" }</tt>.
-h4. Defining Defaults
+### Defining Defaults
You do not need to explicitly use the +:controller+ and +:action+ symbols within a route. You can supply them as defaults:
@@ -471,7 +475,7 @@ get 'photos/:id' => 'photos#show', :defaults => { :format => 'jpg' }
Rails would match +photos/12+ to the +show+ action of +PhotosController+, and set +params[:format]+ to +"jpg"+.
-h4. Naming Routes
+### Naming Routes
You can specify a name for any route using the +:as+ option.
@@ -489,7 +493,7 @@ get ':username', :to => "users#show", :as => :user
This will define a +user_path+ method that will be available in controllers, helpers and views that will go to a route such as +/bob+. Inside the +show+ action of +UsersController+, +params[:username]+ will contain the username for the user. Change +:username+ in the route definition if you do not want your parameter name to be +:username+.
-h4. HTTP Verb Constraints
+### HTTP Verb Constraints
In general, you should use the +get+, +post+, +put+ and +delete+ methods to constrain a route to a particular verb. You can use the +match+ method with the +:via+ option to match multiple verbs at once:
@@ -505,7 +509,7 @@ match 'photos' => 'photos#show', :via => :all
You should avoid routing all verbs to an action unless you have a good reason to, as routing both +GET+ requests and +POST+ requests to a single action has security implications.
-h4. Segment Constraints
+### Segment Constraints
You can use the +:constraints+ option to enforce a format for a dynamic segment:
@@ -534,7 +538,7 @@ get '/:id' => 'posts#show', :constraints => { :id => /\d.+/ }
get '/:username' => 'users#show'
```
-h4. Request-Based Constraints
+### Request-Based Constraints
You can also constrain a route based on any method on the <a href="action_controller_overview.html#the-request-object">Request</a> object that returns a +String+.
@@ -554,7 +558,7 @@ namespace :admin do
end
```
-h4. Advanced Constraints
+### Advanced Constraints
If you have a more advanced constraint, you can provide an object that responds to +matches?+ that Rails should use. Let's say you wanted to route all users on a blacklist to the +BlacklistController+. You could do:
@@ -586,7 +590,7 @@ end
Both the +matches?+ method and the lambda gets the +request+ object as an argument.
-h4. Route Globbing
+### Route Globbing
Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example
@@ -630,7 +634,7 @@ NOTE: If you want to make the format segment mandatory, so it cannot be omitted,
get '*pages' => 'pages#show', :format => true
```
-h4. Redirection
+### Redirection
You can redirect any path to another path using the +redirect+ helper in your router:
@@ -655,7 +659,7 @@ Please note that this redirection is a 301 "Moved Permanently" redirect. Keep in
In all of these cases, if you don't provide the leading host (+http://www.example.com+), Rails will take those details from the current request.
-h4. Routing to Rack Applications
+### Routing to Rack Applications
Instead of a String, like +"posts#index"+, which corresponds to the +index+ action in the +PostsController+, you can specify any <a href="rails_on_rack.html">Rack application</a> as the endpoint for a matcher.
@@ -667,7 +671,7 @@ As long as +Sprockets+ responds to +call+ and returns a <tt>[status, headers, bo
NOTE: For the curious, +"posts#index"+ actually expands out to +PostsController.action(:index)+, which returns a valid Rack application.
-h4. Using +root+
+### Using +root+
You can specify what Rails should route +"/"+ to with the +root+ method:
@@ -680,7 +684,7 @@ You should put the +root+ route at the top of the file, because it is the most p
NOTE: The +root+ route only routes +GET+ requests to the action.
-h4. Unicode character routes
+### Unicode character routes
You can specify unicode character routes directly. For example
@@ -688,11 +692,12 @@ You can specify unicode character routes directly. For example
match 'こんにちは' => 'welcome#index'
```
-h3. Customizing Resourceful Routes
+Customizing Resourceful Routes
+------------------------------
While the default routes and helpers generated by +resources :posts+ will usually serve you well, you may want to customize them in some way. Rails allows you to customize virtually any generic part of the resourceful helpers.
-h4. Specifying a Controller to Use
+### Specifying a Controller to Use
The +:controller+ option lets you explicitly specify a controller to use for the resource. For example:
@@ -713,7 +718,7 @@ will recognize incoming paths beginning with +/photos+ but route to the +Images+
NOTE: Use +photos_path+, +new_photo_path+, etc. to generate paths for this resource.
-h4. Specifying Constraints
+### Specifying Constraints
You can use the +:constraints+ option to specify a required format on the implicit +id+. For example:
@@ -736,7 +741,7 @@ NOTE: Of course, you can use the more advanced constraints available in non-reso
TIP: By default the +:id+ parameter doesn't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within an +:id+ add a constraint which overrides this - for example +:id+ => /[^\/]+/ allows anything except a slash.
-h4. Overriding the Named Helpers
+### Overriding the Named Helpers
The +:as+ option lets you override the normal naming for the named route helpers. For example:
@@ -755,7 +760,7 @@ will recognize incoming paths beginning with +/photos+ and route the requests to
|PATCH/PUT |/photos/:id |update | image_path(:id) |
|DELETE |/photos/:id |destroy | image_path(:id) |
-h4. Overriding the +new+ and +edit+ Segments
+### Overriding the +new+ and +edit+ Segments
The +:path_names+ option lets you override the automatically-generated "new" and "edit" segments in paths:
@@ -780,7 +785,7 @@ scope :path_names => { :new => "make" } do
end
```
-h4. Prefixing the Named Route Helpers
+### Prefixing the Named Route Helpers
You can use the +:as+ option to prefix the named route helpers that Rails generates for a route. Use this option to prevent name collisions between routes using a path scope.
@@ -818,7 +823,7 @@ end
This will provide you with URLs such as +/bob/posts/1+ and will allow you to reference the +username+ part of the path as +params[:username]+ in controllers, helpers and views.
-h4. Restricting the Routes Created
+### Restricting the Routes Created
By default, Rails creates routes for the seven default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option tells Rails to create only the specified routes:
@@ -838,7 +843,7 @@ In this case, Rails will create all of the normal routes except the route for +d
TIP: If your application has many RESTful routes, using +:only+ and +:except+ to generate only the routes that you actually need can cut down on memory use and speed up the routing process.
-h4. Translated Paths
+### Translated Paths
Using +scope+, we can alter path names generated by resources:
@@ -859,7 +864,7 @@ Rails now creates routes to the +CategoriesController+.
|PATCH/PUT |/kategorien/:id |update | category_path(:id) |
|DELETE |/kategorien/:id |destroy | category_path(:id) |
-h4. Overriding the Singular Form
+### Overriding the Singular Form
If you want to define the singular form of a resource, you should add additional rules to the +Inflector+.
@@ -869,7 +874,7 @@ ActiveSupport::Inflector.inflections do |inflect|
end
```
-h4(#nested-names). Using +:as+ in Nested Resources
+### Using +:as+ in Nested Resources
The +:as+ option overrides the automatically-generated name for the resource in nested route helpers. For example,
@@ -881,11 +886,12 @@ end
This will create routing helpers such as +magazine_periodical_ads_url+ and +edit_magazine_periodical_ad_path+.
-h3. Inspecting and Testing Routes
+Inspecting and Testing Routes
+-----------------------------
Rails offers facilities for inspecting and testing your routes.
-h4. Seeing Existing Routes
+### Seeing Existing Routes
To get a complete list of the available routes in your application, visit +http://localhost:3000/rails/info/routes+ in your browser while your server is running in the *development* environment. You can also execute the +rake routes+ command in your terminal to produce the same output.
@@ -913,7 +919,7 @@ $ CONTROLLER=users rake routes
TIP: You'll find that the output from +rake routes+ is much more readable if you widen your terminal window until the output lines don't wrap.
-h4. Testing Routes
+### Testing Routes
Routes should be included in your testing strategy (just like the rest of your application). Rails offers three "built-in assertions":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html designed to make testing routes simpler:
@@ -921,7 +927,7 @@ Routes should be included in your testing strategy (just like the rest of your a
* +assert_recognizes+
* +assert_routing+
-h5. The +assert_generates+ Assertion
+#### The +assert_generates+ Assertion
+assert_generates+ asserts that a particular set of options generate a particular path and can be used with default routes or custom routes.
@@ -930,7 +936,7 @@ assert_generates "/photos/1", { :controller => "photos", :action => "show", :id
assert_generates "/about", :controller => "pages", :action => "about"
```
-h5. The +assert_recognizes+ Assertion
+#### The +assert_recognizes+ Assertion
+assert_recognizes+ is the inverse of +assert_generates+. It asserts that a given path is recognized and routes it to a particular spot in your application.
@@ -944,7 +950,7 @@ You can supply a +:method+ argument to specify the HTTP verb:
assert_recognizes({ :controller => "photos", :action => "create" }, { :path => "photos", :method => :post })
```
-h5. The +assert_routing+ Assertion
+#### The +assert_routing+ Assertion
The +assert_routing+ assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of +assert_generates+ and +assert_recognizes+.