routing.textile 34.0 KB
Newer Older
1 2 3 4
h2. 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:

5
* Understand the code in +routes.rb+
6
* Construct your own routes, using either the preferred resourceful style or the <tt>match</tt> method
7
* Identify what parameters to expect an action to receive
8
* Automatically create paths and URLs using route helpers
9
* Use advanced techniques such as constraints and Rack endpoints
10 11 12

endprologue.

13
h3. The Purpose of the Rails Router
14

15
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.
16 17 18

h4. Connecting URLs to Code

19
When your Rails application receives an incoming request
20

21
<plain>
22
GET /patients/17
23
</plain>
24

25
it asks the router to match it to a controller action. If the first matching route is
26 27

<ruby>
28
match "/patients/:id" => "patients#show"
29 30
</ruby>

31
the request is dispatched to the +patients+ controller's +show+ action with <tt>{ :id => "17" }</tt> in +params+.
32

33
h4. Generating Paths and URLs from Code
34

35
You can also generate paths and URLs. If your application contains this code:
36

37
<ruby>
38
@patient = Patient.find(17)
39 40
</ruby>

41
<erb>
E
eparreno 已提交
42
<%= link_to "Patient Record", patient_path(@patient) %>
43
</erb>
44

E
eparreno 已提交
45
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.
46

47
h3. Resource Routing: the Rails Default
48

49
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.
50

51
h4. Resources on the Web
52

53
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.
54

55
When your Rails application receives an incoming request for
56

57 58 59
<plain>
DELETE /photos/17
</plain>
60

61
it asks the router to map it to a controller action. If the first matching route is
62 63

<ruby>
64
resources :photos
65 66
</ruby>

67
Rails would dispatch that request to the +destroy+ method on the +photos+ controller with <tt>{ :id => "17" }</tt> in +params+.
68 69 70

h4. CRUD, Verbs, and Actions

71
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
72 73

<ruby>
74
resources :photos
75 76
</ruby>

77
creates seven different routes in your application, all mapping to the +Photos+ controller:
78

S
Santiago Pastorino 已提交
79 80 81 82 83 84
|_. HTTP Verb |_.Path            |_.action |_.used for                                   |
|GET          |/photos           |index    |display a list of all photos                 |
|GET          |/photos/new       |new      |return an HTML form for creating a new photo |
|POST         |/photos           |create   |create a new photo                           |
|GET          |/photos/:id       |show     |display a specific photo                     |
|GET          |/photos/:id/edit  |edit     |return an HTML form for editing a photo      |
85
|PATCH/PUT    |/photos/:id       |update   |update a specific photo                      |
S
Santiago Pastorino 已提交
86
|DELETE       |/photos/:id       |destroy  |delete a specific photo                      |
87

88
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.
89

90
h4. Paths and URLs
91

92
Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of +resources :photos+:
93

94 95
* +photos_path+ returns +/photos+
* +new_photo_path+ returns +/photos/new+
96 97
* +edit_photo_path(:id)+ returns +/photos/:id/edit+ (for instance, +edit_photo_path(10)+ returns +/photos/10/edit+)
* +photo_path(:id)+ returns +/photos/:id+ (for instance, +photo_path(10)+ returns +/photos/10+)
98

99
Each of these helpers has a corresponding +_url+ helper (such as +photos_url+) which returns the same path prefixed with the current host, port and path prefix.
100

101
NOTE: Because the router uses the HTTP verb and URL to match inbound requests, four URLs map to seven different actions.
102 103 104

h4. Defining Multiple Resources at the Same Time

105
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+:
106 107

<ruby>
108
resources :photos, :books, :videos
109 110
</ruby>

111
This works exactly the same as
112 113

<ruby>
114 115 116
resources :photos
resources :books
resources :videos
117 118 119 120
</ruby>

h4. Singular Resources

121
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.
122

123 124 125 126 127 128
<ruby>
match "profile" => "users#show"
</ruby>

This resourceful route

129
<ruby>
130
resource :geocoder
131 132
</ruby>

133
creates six different routes in your application, all mapping to the +Geocoders+ controller:
134

S
Santiago Pastorino 已提交
135 136 137 138 139
|_.HTTP Verb |_.Path         |_.action |_.used for                                    |
|GET         |/geocoder/new  |new      |return an HTML form for creating the geocoder |
|POST        |/geocoder      |create   |create the new geocoder                       |
|GET         |/geocoder      |show     |display the one and only geocoder resource    |
|GET         |/geocoder/edit |edit     |return an HTML form for editing the geocoder  |
140
|PATCH/PUT   |/geocoder      |update   |update the one and only geocoder resource     |
S
Santiago Pastorino 已提交
141
|DELETE      |/geocoder      |destroy  |delete the geocoder resource                  |
142

143
NOTE: Because you might want to use the same controller for a singular route (+/account+) and a plural route (+/accounts/45+), singular resources map to plural controllers.
144

145
A singular resourceful route generates these helpers:
146

147 148 149
* +new_geocoder_path+ returns +/geocoder/new+
* +edit_geocoder_path+ returns +/geocoder/edit+
* +geocoder_path+ returns +/geocoder+
150

151
As with plural resources, the same helpers ending in +_url+ will also include the host, port and path prefix.
152 153 154

h4. Controller Namespaces and Routing

155
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:
156 157

<ruby>
158
namespace :admin do
159
  resources :posts, :comments
160 161 162
end
</ruby>

163
This will create a number of routes for each of the +posts+ and +comments+ controller. For +Admin::PostsController+, Rails will create:
164

165 166 167 168 169 170
|_.HTTP Verb |_.Path                |_.action |_.named helper             |
|GET         |/admin/posts          |index    | admin_posts_path          |
|GET         |/admin/posts/new      |new      | new_admin_post_path       |
|POST        |/admin/posts          |create   | admin_posts_path          |
|GET         |/admin/posts/:id      |show     | admin_post_path(:id)      |
|GET         |/admin/posts/:id/edit |edit     | edit_admin_post_path(:id) |
171
|PATCH/PUT   |/admin/posts/:id      |update   | admin_post_path(:id)      |
172
|DELETE      |/admin/posts/:id      |destroy  | admin_post_path(:id)      |
173

174
If you want to route +/posts+ (without the prefix +/admin+) to +Admin::PostsController+, you could use
175 176

<ruby>
177 178 179
scope :module => "admin" do
  resources :posts, :comments
end
180 181
</ruby>

182
or, for a single case
183 184

<ruby>
185
resources :posts, :module => "admin"
186 187
</ruby>

188
If you want to route +/admin/posts+ to +PostsController+ (without the +Admin::+ module prefix), you could use
189 190

<ruby>
191 192 193
scope "/admin" do
  resources :posts, :comments
end
194 195
</ruby>

196
or, for a single case
197 198

<ruby>
199
resources :posts, :path => "/admin/posts"
200 201
</ruby>

202
In each of these cases, the named routes remain the same as if you did not use +scope+. In the last case, the following paths map to +PostsController+:
203

S
Santiago Pastorino 已提交
204 205
|_.HTTP Verb |_.Path               |_.action |_.named helper      |
|GET         |/admin/posts         |index    | posts_path         |
206
|GET         |/admin/posts/new     |new      | new_post_path      |
S
Santiago Pastorino 已提交
207
|POST        |/admin/posts         |create   | posts_path         |
208 209
|GET         |/admin/posts/:id     |show     | post_path(:id)     |
|GET         |/admin/posts/:id/edit|edit     | edit_post_path(:id)|
210
|PATCH/PUT   |/admin/posts/:id     |update   | post_path(:id)     |
211
|DELETE      |/admin/posts/:id     |destroy  | post_path(:id)     |
212

213 214 215 216 217 218 219 220 221 222 223 224 225 226
h4. Nested Resources

It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:

<ruby>
class Magazine < ActiveRecord::Base
  has_many :ads
end

class Ad < ActiveRecord::Base
  belongs_to :magazine
end
</ruby>

227
Nested routes allow you to capture this relationship in your routing. In this case, you could include this route declaration:
228 229

<ruby>
230 231
resources :magazines do
  resources :ads
232 233 234
end
</ruby>

235
In addition to the routes for magazines, this declaration will also route ads to an +AdsController+. The ad URLs require a magazine:
236

237 238 239 240
|_.HTTP Verb |_.Path                      |_.action |_.used for                                                                 |
|GET         |/magazines/:id/ads          |index    |display a list of all ads for a specific magazine                          |
|GET         |/magazines/:id/ads/new      |new      |return an HTML form for creating a new ad belonging to a specific magazine |
|POST        |/magazines/:id/ads          |create   |create a new ad belonging to a specific magazine                           |
241 242
|GET         |/magazines/:id/ads/:id      |show     |display a specific ad belonging to a specific magazine                     |
|GET         |/magazines/:id/ads/:id/edit |edit     |return an HTML form for editing an ad belonging to a specific magazine     |
243
|PATCH/PUT   |/magazines/:id/ads/:id      |update   |update a specific ad belonging to a specific magazine                      |
244
|DELETE      |/magazines/:id/ads/:id      |destroy  |delete a specific ad belonging to a specific magazine                      |
245

246
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)+).
247 248 249 250 251 252

h5. Limits to Nesting

You can nest resources within other nested resources if you like. For example:

<ruby>
253 254 255
resources :publishers do
  resources :magazines do
    resources :photos
256 257 258 259
  end
end
</ruby>

260
Deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize paths such as
261 262 263 264 265 266 267

<pre>
/publishers/1/magazines/2/photos/3
</pre>

The corresponding route helper would be +publisher_magazine_photo_url+, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular "article":http://weblog.jamisbuck.org/2007/2/5/nesting-resources by Jamis Buck proposes a rule of thumb for good Rails design:

268
TIP: _Resources should never be nested more than 1 level deep._
269

270
h4. Creating Paths and URLs From Objects
271

272
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:
273 274

<ruby>
275 276
resources :magazines do
  resources :ads
277 278 279
end
</ruby>

280
When using +magazine_ad_path+, you can pass in instances of +Magazine+ and +Ad+ instead of the numeric IDs.
281

282
<erb>
283
<%= link_to "Ad details", magazine_ad_path(@magazine, @ad) %>
284
</erb>
285

286
You can also use +url_for+ with a set of objects, and Rails will automatically determine which route you want:
287

288
<erb>
289
<%= link_to "Ad details", url_for([@magazine, @ad]) %>
290
</erb>
291

292
In this case, Rails will see that +@magazine+ is a +Magazine+ and +@ad+ is an +Ad+ and will therefore use the +magazine_ad_path+ helper. In helpers like +link_to+, you can specify just the object in place of the full +url_for+ call:
293

294 295 296
<erb>
<%= link_to "Ad details", [@magazine, @ad] %>
</erb>
297

V
Vijay Dev 已提交
298
If you wanted to link to just a magazine:
299

300 301 302
<erb>
<%= link_to "Magazine details", @magazine %>
</erb>
303

V
Vijay Dev 已提交
304
For other actions, you just need to insert the action name as the first element of the array:
305 306 307 308 309

<erb>
<%= link_to "Edit Ad", [:edit, @magazine, @ad] %>
</erb>

310
This allows you to treat instances of your models as URLs, and is a key advantage to using the resourceful style.
311 312 313

h4. Adding More RESTful Actions

314
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.
315 316 317

h5. Adding Member Routes

318
To add a member route, just add a +member+ block into the resource block:
319 320

<ruby>
321 322
resources :photos do
  member do
323
    get 'preview'
324 325
  end
end
326 327
</ruby>

328
This will recognize +/photos/1/preview+ with GET, and route to the +preview+ action of +PhotosController+. It will also create the +preview_photo_url+ and +preview_photo_path+ helpers.
329

330
Within the block of member routes, each route name specifies the HTTP verb that it will recognize. You can use +get+, +patch+, +put+, +post+, or +delete+ here. If you don't have multiple +member+ routes, you can also pass +:on+ to a route, eliminating the block:
331 332

<ruby>
333
resources :photos do
334
  get 'preview', :on => :member
335
end
336 337 338 339
</ruby>

h5. Adding Collection Routes

340
To add a route to the collection:
341 342

<ruby>
343 344
resources :photos do
  collection do
345
    get 'search'
346 347
  end
end
348 349
</ruby>

350
This will enable Rails to recognize paths such as +/photos/search+ with GET, and route to the +search+ action of +PhotosController+. It will also create the +search_photos_url+ and +search_photos_path+ route helpers.
351

352
Just as with member routes, you can pass +:on+ to a route:
353 354

<ruby>
355
resources :photos do
356
  get 'search', :on => :collection
357
end
358 359 360 361
</ruby>

h5. A Note of Caution

362
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.
363

364
h3. Non-Resourceful Routes
365

366
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.
367

368 369 370
While you should usually use resourceful routing, there are still many places where the simpler routing is more appropriate. There's no need to try to shoehorn every last piece of your application into a resourceful framework if that's not a good fit.

In particular, simple routing makes it very easy to map legacy URLs to new Rails actions.
371 372 373 374 375 376

h4. 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:

<ruby>
377
match ':controller(/:action(/:id))'
378 379
</ruby>

E
eparreno 已提交
380
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.
381

382
h4. Dynamic Segments
383

384
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:
385 386

<ruby>
387
match ':controller/:action/:id/:user_id'
388 389
</ruby>

390
An incoming path of +/photos/show/1/2+ will be dispatched to the +show+ action of the +PhotosController+. +params[:id]+ will be +"1"+, and +params[:user_id]+ will be +"2"+.
391

392 393 394 395 396 397
NOTE: You can't use +namespace+ or +:module+ with a +:controller+ path segment. If you need to do this then use a constraint on :controller that matches the namespace you require. e.g:

<ruby>
match ':controller(/:action(/:id))', :controller => /admin\/[^\/]+/
</ruby>

398
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 which overrides this - for example +:id+ => /[^\/]+/ allows anything except a slash.
399

400
h4. Static Segments
401

402
You can specify static segments when creating a route:
403 404

<ruby>
405
match ':controller/:action/:id/with_user/:user_id'
406 407
</ruby>

408
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>.
409

410
h4. The Query String
411

412
The +params+ will also include any parameters from the query string. For example, with this route:
413 414

<ruby>
415
match ':controller/:action/:id'
416 417
</ruby>

418
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>.
419 420 421

h4. Defining Defaults

422
You do not need to explicitly use the +:controller+ and +:action+ symbols within a route. You can supply them as defaults:
423 424

<ruby>
425
match 'photos/:id' => 'photos#show'
426 427
</ruby>

428
With this route, Rails will match an incoming path of +/photos/12+ to the +show+ action of +PhotosController+.
429

430
You can also define other defaults in a route by supplying a hash for the +:defaults+ option. This even applies to parameters that you do not specify as dynamic segments. For example:
431 432

<ruby>
433
match 'photos/:id' => 'photos#show', :defaults => { :format => 'jpg' }
434 435
</ruby>

436
Rails would match +photos/12+ to the +show+ action of +PhotosController+, and set +params[:format]+ to +"jpg"+.
437

438
h4. Naming Routes
439

440
You can specify a name for any route using the +:as+ option.
441 442

<ruby>
443
match 'exit' => 'sessions#destroy', :as => :logout
444 445
</ruby>

E
eparreno 已提交
446
This will create +logout_path+ and +logout_url+ as named helpers in your application. Calling +logout_path+ will return +/exit+
447

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
h4. HTTP Verb Constraints

You can use the +:via+ option to constrain the request to one or more HTTP methods:

<ruby>
match 'photos/show' => 'photos#show', :via => :get
</ruby>

There is a shorthand version of this as well:

<ruby>
get 'photos/show'
</ruby>

You can also permit more than one verb to a single route:

<ruby>
match 'photos/show' => 'photos#show', :via => [:get, :post]
</ruby>

468
h4. Segment Constraints
469

470
You can use the +:constraints+ option to enforce a format for a dynamic segment:
471 472

<ruby>
473
match 'photos/:id' => 'photos#show', :constraints => { :id => /[A-Z]\d{5}/ }
474 475
</ruby>

476
This route would match paths such as +/photos/A12345+. You can more succinctly express the same route this way:
477 478

<ruby>
479
match 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/
480 481
</ruby>

482
+:constraints+ takes regular expressions with the restriction that regexp anchors can't be used. For example, the following route will not work:
483 484

<ruby>
485 486 487 488 489 490 491 492 493 494
match '/:id' => 'posts#show', :constraints => {:id => /^\d/}
</ruby>

However, note that you don't need to use anchors because all routes are anchored at the start.

For example, the following routes would allow for +posts+ with +to_param+ values like +1-hello-world+ that always begin with a number and +users+ with +to_param+ values like +david+ that never begin with a number to share the root namespace:

<ruby>
match '/:id' => 'posts#show', :constraints => { :id => /\d.+/ }
match '/:username' => 'users#show'
495 496
</ruby>

497 498 499 500 501 502 503
h4. 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+.

You specify a request-based constraint the same way that you specify a segment constraint:

<ruby>
504
match "photos", :constraints => {:subdomain => "admin"}
505 506
</ruby>

V
Vijay Dev 已提交
507
You can also specify constraints in a block form:
508 509

<ruby>
510
namespace :admin do
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
  constraints :subdomain => "admin" do
    resources :photos
  end
end
</ruby>

h4. 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:

<ruby>
class BlacklistConstraint
  def initialize
    @ips = Blacklist.retrieve_ips
  end

  def matches?(request)
    @ips.include?(request.remote_ip)
  end
end

TwitterClone::Application.routes.draw do
533
  match "*path" => "blacklist#index",
534 535 536 537
    :constraints => BlacklistConstraint.new
end
</ruby>

538 539 540 541 542
h4. 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

<ruby>
543
match 'photos/*other' => 'photos#unknown'
544 545
</ruby>

546
This route would match +photos/12+ or +/photos/long/path/to/12+, setting +params[:other]+ to +"12"+ or +"long/path/to/12"+.
547

548
Wildcard segments can occur anywhere in a route. For example,
549 550 551 552 553 554 555

<ruby>
match 'books/*section/:title' => 'books#show'
</ruby>

would match +books/some/section/last-words-a-memoir+ with +params[:section]+ equals +"some/section"+, and +params[:title]+ equals +"last-words-a-memoir"+.

556
Technically a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example,
557 558 559 560 561 562 563

<ruby>
match '*a/foo/*b' => 'test#index'
</ruby>

would match +zoo/woo/foo/bar/baz+ with +params[:a]+ equals +"zoo/woo"+, and +params[:b]+ equals +"bar/baz"+.

564
NOTE: Starting from Rails 3.1, wildcard routes will always match the optional format segment by default. For example if you have this route:
565 566

<ruby>
567
match '*pages' => 'pages#show'
568 569 570 571 572
</ruby>

NOTE: By requesting +"/foo/bar.json"+, your +params[:pages]+ will be equals to +"foo/bar"+ with the request format of JSON. If you want the old 3.0.x behavior back, you could supply +:format => false+ like this:

<ruby>
573
match '*pages' => 'pages#show', :format => false
574 575
</ruby>

576 577 578 579 580 581
NOTE: If you want to make the format segment mandatory, so it cannot be omitted, you can supply +:format => true+ like this:

<ruby>
match '*pages' => 'pages#show', :format => true
</ruby>

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
h4. Redirection

You can redirect any path to another path using the +redirect+ helper in your router:

<ruby>
match "/stories" => redirect("/posts")
</ruby>

You can also reuse dynamic segments from the match in the path to redirect to:

<ruby>
match "/stories/:name" => redirect("/posts/%{name}")
</ruby>

You can also provide a block to redirect, which receives the params and (optionally) the request object:
597

598 599 600 601 602
<ruby>
match "/stories/:name" => redirect {|params| "/posts/#{params[:name].pluralize}" }
match "/stories" => redirect {|p, req| "/posts/#{req.subdomain}" }
</ruby>

603
Please note that this redirection is a 301 "Moved Permanently" redirect. Keep in mind that some web browsers or proxy servers will cache this type of redirect, making the old page inaccessible.
604

605
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.
606

607
h4. Routing to Rack Applications
608

609
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.
610 611

<ruby>
612
match "/application.js" => Sprockets
613 614
</ruby>

615 616 617 618 619 620 621
As long as +Sprockets+ responds to +call+ and returns a <tt>[status, headers, body]</tt>, the router won't know the difference between the Rack application and an action.

NOTE: For the curious, +"posts#index"+ actually expands out to +PostsController.action(:index)+, which returns a valid Rack application.

h4. Using +root+

You can specify what Rails should route +"/"+ to with the +root+ method:
622 623

<ruby>
624
root :to => 'pages#main'
625
root 'pages#main' # shortcut for the above
626 627
</ruby>

628
You should put the +root+ route at the top of the file, because it is the most popular route and should be matched first. You also need to delete the +public/index.html+ file for the root route to take effect.
629 630 631 632 633 634 635 636 637 638 639 640 641

h3. 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

The +:controller+ option lets you explicitly specify a controller to use for the resource. For example:

<ruby>
resources :photos, :controller => "images"
</ruby>

642
will recognize incoming paths beginning with +/photos+ but route to the +Images+ controller:
643

644 645 646 647 648 649
|_.HTTP Verb |_.Path           |_.action |_.named helper        |
|GET         |/photos          |index    | photos_path          |
|GET         |/photos/new      |new      | new_photo_path       |
|POST        |/photos          |create   | photos_path          |
|GET         |/photos/:id      |show     | photo_path(:id)      |
|GET         |/photos/:id/edit |edit     | edit_photo_path(:id) |
650
|PATCH/PUT   |/photos/:id      |update   | photo_path(:id)      |
651
|DELETE      |/photos/:id      |destroy  | photo_path(:id)      |
652

653
NOTE: Use +photos_path+, +new_photo_path+, etc. to generate paths for this resource.
654 655 656 657 658 659

h4. Specifying Constraints

You can use the +:constraints+ option to specify a required format on the implicit +id+. For example:

<ruby>
660
resources :photos, :constraints => {:id => /[A-Z][A-Z][0-9]+/}
661 662
</ruby>

R
Ryan Sandridge 已提交
663
This declaration constrains the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match.
664

665
You can specify a single constraint to apply to a number of routes by using the block form:
666 667

<ruby>
668
constraints(:id => /[A-Z][A-Z][0-9]+/) do
669 670 671 672 673
  resources :photos
  resources :accounts
end
</ruby>

674
NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context.
675

676
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.
677

678 679 680 681 682 683 684 685
h4. Overriding the Named Helpers

The +:as+ option lets you override the normal naming for the named route helpers. For example:

<ruby>
resources :photos, :as => "images"
</ruby>

686
will recognize incoming paths beginning with +/photos+ and route the requests to +PhotosController+, but use the value of the :as option to name the helpers.
687

688 689 690 691 692 693
|_.HTTP verb|_.Path            |_.action |_.named helper        |
|GET        |/photos           |index    | images_path          |
|GET        |/photos/new       |new      | new_image_path       |
|POST       |/photos           |create   | images_path          |
|GET        |/photos/:id       |show     | image_path(:id)      |
|GET        |/photos/:id/edit  |edit     | edit_image_path(:id) |
694
|PATCH/PUT  |/photos/:id       |update   | image_path(:id)      |
695
|DELETE     |/photos/:id       |destroy  | image_path(:id)      |
696 697 698

h4. Overriding the +new+ and +edit+ Segments

699
The +:path_names+ option lets you override the automatically-generated "new" and "edit" segments in paths:
700 701 702 703 704

<ruby>
resources :photos, :path_names => { :new => 'make', :edit => 'change' }
</ruby>

705
This would cause the routing to recognize paths such as
706

W
wycats 已提交
707
<plain>
708 709
/photos/make
/photos/1/change
W
wycats 已提交
710
</plain>
711

712
NOTE: The actual action names aren't changed by this option. The two paths shown would still route to the +new+ and +edit+ actions.
713

714
TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can use a scope.
715 716 717 718

<ruby>
scope :path_names => { :new => "make" } do
  # rest of your routes
719 720 721
end
</ruby>

722
h4. Prefixing the Named Route Helpers
723

724
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.
725

726 727
<ruby>
scope "admin" do
728
  resources :photos, :as => "admin_photos"
729
end
730

731 732 733
resources :photos
</ruby>

734
This will provide route helpers such as +admin_photos_path+, +new_admin_photo_path+ etc.
735

736
To prefix a group of route helpers, use +:as+ with +scope+:
737 738

<ruby>
739
scope "admin", :as => "admin" do
740 741 742 743
  resources :photos, :accounts
end

resources :photos, :accounts
744 745
</ruby>

746
This will generate routes such as +admin_photos_path+ and +admin_accounts_path+ which map to +/admin/photos+ and +/admin/accounts+ respectively.
747

748
NOTE: The +namespace+ scope will automatically add +:as+ as well as +:module+ and +:path+ prefixes.
749

750 751 752 753 754 755 756 757 758 759
You can prefix routes with a named parameter also:

<ruby>
scope ":username" do
  resources :posts
end
</ruby>

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.

760
h4. Restricting the Routes Created
761

762
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:
763 764

<ruby>
765
resources :photos, :only => [:index, :show]
766 767
</ruby>

768 769 770
Now, a +GET+ request to +/photos+ would succeed, but a +POST+ request to +/photos+ (which would ordinarily be routed to the +create+ action) will fail.

The +:except+ option specifies a route or list of routes that Rails should _not_ create:
771

772 773 774
<ruby>
resources :photos, :except => :destroy
</ruby>
775

776
In this case, Rails will create all of the normal routes except the route for +destroy+ (a +DELETE+ request to +/photos/:id+).
777

778
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.
779

780
h4. Translated Paths
781

782
Using +scope+, we can alter path names generated by resources:
783 784

<ruby>
785 786 787
scope(:path_names => { :new => "neu", :edit => "bearbeiten" }) do
  resources :categories, :path => "kategorien"
end
788 789
</ruby>

790
Rails now creates routes to the +CategoriesController+.
791

792 793 794 795 796 797
|_.HTTP verb|_.Path                     |_.action |_.named helper           |
|GET        |/kategorien                |index    | categories_path         |
|GET        |/kategorien/neu            |new      | new_category_path       |
|POST       |/kategorien                |create   | categories_path         |
|GET        |/kategorien/:id            |show     | category_path(:id)      |
|GET        |/kategorien/:id/bearbeiten |edit     | edit_category_path(:id) |
798
|PATCH/PUT  |/kategorien/:id            |update   | category_path(:id)      |
799
|DELETE     |/kategorien/:id            |destroy  | category_path(:id)      |
800

801
h4. Overriding the Singular Form
802

803
If you want to define the singular form of a resource, you should add additional rules to the +Inflector+.
804 805

<ruby>
806 807 808
ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'tooth', 'teeth'
end
809 810
</ruby>

811
h4(#nested-names). Using +:as+ in Nested Resources
812

813
The +:as+ option overrides the automatically-generated name for the resource in nested route helpers. For example,
814 815 816

<ruby>
resources :magazines do
817
  resources :ads, :as => 'periodical_ads'
818
end
819 820
</ruby>

821
This will create routing helpers such as +magazine_periodical_ads_url+ and +edit_magazine_periodical_ad_path+.
822 823 824

h3. Inspecting and Testing Routes

825
Rails offers facilities for inspecting and testing your routes.
826

827
h4. Seeing Existing Routes with +rake+
828

829
If you want a complete list of all of the available routes in your application, run +rake routes+ command. This will print all of your routes, in the same order that they appear in +routes.rb+. For each route, you'll see:
830 831 832

* The route name (if any)
* The HTTP verb used (if the route doesn't respond to all verbs)
833 834
* The URL pattern to match
* The routing parameters for the route
835 836 837 838

For example, here's a small section of the +rake routes+ output for a RESTful route:

<pre>
839 840 841 842
    users GET    /users(.:format)          users#index
          POST   /users(.:format)          users#create
 new_user GET    /users/new(.:format)      users#new
edit_user GET    /users/:id/edit(.:format) users#edit
843 844
</pre>

845 846 847
You may restrict the listing to the routes that map to a particular controller setting the +CONTROLLER+ environment variable:

<shell>
848
$ CONTROLLER=users rake routes
849 850
</shell>

851 852 853 854
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

855
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:
856 857 858 859 860 861 862

* +assert_generates+
* +assert_recognizes+
* +assert_routing+

h5. The +assert_generates+ Assertion

863
+assert_generates+ asserts that a particular set of options generate a particular path and can be used with default routes or custom routes.
864 865 866 867 868 869 870 871

<ruby>
assert_generates "/photos/1", { :controller => "photos", :action => "show", :id => "1" }
assert_generates "/about", :controller => "pages", :action => "about"
</ruby>

h5. The +assert_recognizes+ Assertion

872
+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.
873 874

<ruby>
875
assert_recognizes({ :controller => "photos", :action => "show", :id => "1" }, "/photos/1")
876 877 878 879 880
</ruby>

You can supply a +:method+ argument to specify the HTTP verb:

<ruby>
881
assert_recognizes({ :controller => "photos", :action => "create" }, { :path => "photos", :method => :post })
882 883 884 885 886 887 888
</ruby>

h5. 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+.

<ruby>
889
assert_routing({ :path => "photos", :method => :post }, { :controller => "photos", :action => "create" })
890
</ruby>