Francis's Octopress Blog

A blogging framework for hackers.

Rails Routing From the Outside in Rails

Rails Routing from the Outside In Rails

Rails Routing from the Outside In Rails来自外部的Routing

This guide covers the user-facing features of Rails routing. By referring to this guide, you will be able to:

这个guide涵盖了面向用户的Rails路由特性。通过参考这个guide,你将能够:

Understand the code in routes.rb

明白在routes.rb中的代码

  • Construct your own routes, using either the preferred resourceful style or the match method

构建属于你的routes,要么首选使用resourceful style要么使用match方法

  • Identify what parameters to expect an action to receive

确定什么样的参数expect(预期)一个action来接收(url

  • Automatically create paths and URLs using route helpers

自动的创建路径和URLs使用route helpers

  • Use advanced techniques such as constraints and Rack endpoints

使用高级的技术比如公约和Rack endpoints

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

Rails router组织URLsdispatches(调度)到一个controlleraction中。它也可以创建pathsURLs,避免需要hardcode string到你的视图中。

1.1 Connecting URLs to Code连接URLsCode

When your Rails application receives an incoming request

当你的Rails应用程序收到一个传入请求(incoming requests (传入请求)正传递给用户的网站内容。)

GET /patients/17

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

它请求router匹配URLs到一个controller action。如果第一个匹配的route

match “/patients/:id” => “patients#show”

the request is dispatched to the patients controller’s show action with { :id =>17} in params.

这个请求被调度给patients controllershow action以及{ :id =>17}params字典中。

1.2 Generating Paths and URLs from CodeCode创建PathsURLs

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

你可以创建pathsURLs。如果你的应用程序中包含这样的代码:

@patient = Patient.find(17)

<%= link_to “Patient Record”, patient_path(@patient) %>

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.

Router将会创建path /patients/17。这样减少了你的视图的脆性并且使得你的代码更加容易明白。

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

Resource routing让你快速的为一个提供的resourcefulcontroller声明所有的常用routes。替代你去声明单个的index, show, new, edit, create, update and destroy actionsroutes,一个resourceful route声明它们在一个单行代码中。

When your Rails application receives an incoming request for

当你的Rails应用程序收到一个这样的传入请求

DELETE /photos/17

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

它请求router匹配URLs到一个controller action。如果第一个匹配的route

resources :photos

Rails would dispatch that request to the destroy method on the photos controller with { :id =>17} in params.

Rails将会把这个请求调度给photos controllerdestroy action以及{ :id =>17}params字典中

2.2 CRUD, Verbs, and Actions

CRUD是指在做计算处理时的增加(Create)、查询(Retrieve)(重新得到数据)、更新(Update)和删除(Delete)几个单词的首字母简写。主要被用在描述软件系统中数据库或者持久层的基本操作功能。

HTTP Verb HTTP动作

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

Rails中,一个resourceful route提供一个在HTTP verbsURLs之间的映射到controller actions。根据公约,每个action都应该映射到数据库的CRUD操作的一部分。一个单独的条目在routing文件中,像这样

resources :photos

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

创建七个不同的routes在你的应用程序中,所有的这些routes映射到Photos controller

 

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
PUT /photos/:id update update a specific photo
DELETE /photos/:id destroy delete a specific photo

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.

Rails routes在它们指定的顺序中匹配,因此如果你有一个resources :photosget ‘photos/poll’的上面,resources lineshow actionroute将会在get line之前先被匹配。要修复这些,移动get lineresources line上面以确保get line被首先匹配。

2.3 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:

在你的应用程序中创建一个resourcefulroute也将会摆出一系列的controllershelpers,在这里的情况中resources :photos如下:

  • photos_path returns /photos
  • new_photo_path returns /photos/new
  • 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)

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.

这里的每个helpers都有一个相应的_url helper(例如photos_urledit_photo_url(1)

其将会返回相同的路径后缀以及当前主机,端口和路径后缀。

the code in my demo

@tmp=post_url(1)

@tmp=posts_url

@tmp=edit_post_url(:id)

@tmp=new_post_url

Because the router uses the HTTP verb and URL to match inbound requests, four URLs map to seven different actions.

因为router使用HTTP verbURL来匹配入站请求,四种URLs映射到七种不同的actions中。

2.4 Defining Multiple Resources at the Same Time在同一时间定义多个Resource

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:

如果你需要为超过一个resource创建routes,你可以保存它们到一组中通过调用单个resources来定义所有的resource

resources :photos, :books, :videos

This works exactly the same as

这里工作类似于:

resources :photos

resources :books

resources :videos

2.5 Singular Resources 单数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.

有时候,你有一个resourceclients通常查找它们并不引用一个ID。例如,你将会希望/profile来总是显示当前的登录的用户的profile。在这种情况中,你可以使用一个单数的resource来映射/profile (rather than /profile/:id)show ation

match “profile” => “users#show”

This resourceful route这里是resourceful route

resource :geocoder

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

在你的应用程序中创建六种不同的routes,所有的routes映射到Geocoderscotroller

 

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
PUT /geocoder update update the one and only geocoder resource
DELETE /geocoder destroy delete the geocoder resource

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.

因为你可能希望对单数route(/account)和复数route(/accounts/45)使用相同的controller,单数resources映射到复数controllers

A singular resourceful route generates these helpers:

一个单数resourceful route创建这些helpers

  • new_geocoder_path returns /geocoder/new
  • edit_geocoder_path returns /geocoder/edit
  • geocoder_path returns /geocoder

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

就像plural resources,相同的以_url结尾的helpers同样包含,hostport和路径后缀。

2.6 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:

你可能希望通过namespace分组组织controllers。通常大多数情况,你可以分组一系列的administrative controllers到一个Admin::名称空间下面。你将会放置这些controllersapp/controllers/admin目录中,并且你可以在你的router中分组他们在一起

namespace :admin do

resources :posts, :comments

end

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

这将会对于每一个postscomments controller创建若干的routes。对于Admin::PostsControllerRails将会创建:

 

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)
PUT /admin/posts/:id update admin_post_path(:id)
DELETE /admin/posts/:id destroy admin_post_path(:id)

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

如果你想Admin::PostsControllerroute /posts(without the prefix /admin),你可以使用

#admin中取出,重新声明为独立的resources

scope :module => “admin” do

resources :posts, :comments

end

or, for a single case

resources :posts, :module => “admin”

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

scope “/admin” do

resources :posts, :comments

end

or, for a single case

resources :posts, :path => “/admin/posts”

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:

在每个这样的情况中,named routes保持不变,如果你没有使用范围。在最后,随后的paths映射到PostsController

 

HTTP Verb Path action named helper
GET /admin/posts index posts_path
GET /admin/posts/new new new_post_path
POST /admin/posts create posts_path
GET /admin/posts/:id show post_path(:id)
GET /admin/posts/:id/edit edit edit_post_path(:id)
PUT /admin/posts/:id update post_path(:id)
DELETE /admin/posts/:id destroy post_path(:id)

2.7 Nested Resources嵌套Resource

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

在通常情况中有resources是其他的resources逻辑上的children。例如,假设你的应用程序包含这些models

class Magazine < ActiveRecord::Base

has_many :ads

end

 

class Ad < ActiveRecord::Base

belongs_to :magazine

end

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

嵌套routes允许你捕捉这些关系在你的routing中。在这里的情况中,你可包含这样的声明:

resources :magazines do

resources :ads

end

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

除了magazinesroutes,这里也同样声明route adsAdsControlleradURLs需要一个magazine(对象):

 

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
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
PUT /magazines/:id/ads/:id update update a specific ad belonging to a specific magazine
DELETE /magazines/:id/ads/:id destroy delete a specific ad belonging to a specific magazine

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

这里也将会创建routing helpers例如magazine_ads_urledit_magazine_ad_path。这些helpers获取一个Magazine的实例作为第一个参数(magazine_ads_url(@magazine))。

2.7.1 Limits to Nesting嵌套的局限

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

你可以嵌套resources在其他嵌套resources中如果你喜欢。例如:

resources :publishers do

resources :magazines do

resources :photos

end

end

Deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize paths such as

深层的嵌套resources相当的累赘。在这样的情况下,例如,应用程序将会这样组织路径

/publishers/1/magazines/2/photos/3

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 by Jamis Buck proposes a rule of thumb for good Rails design:

相应的route helper将会是publisher_magazine_photo_url这需要你指定三个级别的所有对象。事实上,这种情况下太混乱了一篇受欢迎的文章来自Jamis Buck,关于一个设计良好的Rails的经验法则:

Resources should never be nested more than 1 level deep.

2.8 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:

除了使用routing helpersRails也可以从一个parameters数组创建pathsURLs。例如,假设你有这样的组routes

resources :magazines do

resources :ads

end

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

在使用magazine_ad_path的时候,你可以传递Magazine and Ad的实例替代数字IDs

<%= link_to “Ad details”, magazine_ad_path(@magazine, @ad) %>

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

你同样也可以使用url_for和一组对象,那么Rails将会自动的决定那个route是你希望的:

<%= link_to “Ad details”, url_for([@magazine, @ad]) %>

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:

在这里,Rails将会明白@magazineMagazine并且@adAd于此将会因此使用magazine_ad_path helper。在就像link_tohelpers中,你可以指定仅仅对象在url_for调用中:

<%= link_to “Ad details”, [@magazine, @ad] %>

If you wanted to link to just a magazine, you could leave out the Array:

如果你想仅仅link到一个magazine,你可以省去数组:

<%= link_to “Magazine details”, @magazine %>

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

这让你处理models的实例为URLs,并且这也是使用resourceful style的关键优势。

2.9 Adding More RESTful Actions添加更多的RESTful Action

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.

你并不限制于RESTful routing默认创建的七个routes。如果你喜欢,你可以添加额外的routes用于多个或者个别的collection

2.9.1 Adding Member Routes

To add a member route, just add a member block into the resource block:

添加一个member route,仅仅添加一个memberblockresource block中:

resources :photos do

member do

get ‘preview’

end

end

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.

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

memberroutes中,每个route名字指定HTTP verb这是将会组织的。在这里你可以使用get, put, post, or delete。如果你没有多个member routes,你同样也可以传递:on到一个route,消除block

resources :photos do

get ‘preview’, :on => :member

end

2.9.2 Adding Collection Routes

To add a route to the collection:

添加一个routecollection

resources :photos do

collection do

get ‘search’

end

end

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.

这将使Rails能够像这样/photos/search with GET组织路径,并且routePhotosControllersearch action。它将同样创建search_photos_urlsearch_photos_path route helpers

Just as with member routes, you can pass :on to a route:

仅仅对于member routes,你可以传递:on给一个route

resources :photos do

get ‘search’, :on => :collection

end

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

如果你发现你自己添加很多额外的action到一个resourcefulroute,是时候停下来并问你自己

是否你在伪造另一个resource

3 Non-Resourceful Routes- 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.

除了resource routingRails对任意的URLsactions有强力的支持。这里,你没有得到被resourceful routing自动创建的groups of routes。作为替代,在你的应用程序中分别设置每个route

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.

即使你应该通常使用resourceful routing,这里仍然有很多地方简单的routing更加适合。这里不需要尝试将你的应用程序最后写成一个resourceful framework如果这样并不合适。

In particular, simple routing makes it very easy to map legacy URLs to new Rails actions.

特别是,简单的路routing,使得它很容易映射(传入的)现有的URL映射到新的Rails action

3.1 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:

当你设定一个正则route,你供应一系列的字符,其将通过Rails映射到传入HTTP请求的一部分。这些字符的两部分分别是::controller映射到你应用程序中的一个controller,并且:action映射到在指定的controller中的一个action。例如思考一个默认的Rails routes

match ‘: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.

如果传入请求/photos/show/1 is processed by this route (因为它并没有被先前的route文件中任何的route匹配成功),接着这个结果将会调用PhotosControllershow action,并且使得最后的参数1可用于params[:id]。这个route也还会route传入请求/photosPhotosController#index,因为:action:id是被括号包起来的可选参数。

3.2 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:

你可以设置你希望的数目的dynamic segments在一个正则route中。超过:controller or :action的其他部分(是可用的)在action作为params第一部分。如果你设定这样的route

match ‘:controller/:action/:id/:user_id’

An incoming path of /photos/show/½ will be dispatched to the show action of the PhotosController. params[:id] will be “1”, and params[:user_id] will be “2”.

一个传入路径/photos/show/½将会被调度给PhotosControllershow actionparams[:id] will be “1”, and params[:user_id] will be “2”.

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:

你不能对一个:controller路径segment使用namespace或者:module。如果你需要这么做那么使用对:controller一个限制使其匹配你请求的namespace。例如:

match ‘:controller(/:action(/:id))’, :controller => /admin\/[^\/]+/

 

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.

默认的动态分割不接受dots.——这是因为dot被作为格式化routes的一个分割。如果你需要在一个dynamic segment中使用dot,添加一个限制来重写它——例如:id => /[^\/]+/允许除了斜线之外的任何字符。

3.3 Static Segments

You can specify static segments when creating a route:

match ‘: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 { :controller =>photos, :action =>show, :id =>1, :user_id =>2}.

3.4 The Query String查询字符串

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

params将也会包含来自查询字符串的任何参数。例如,使用这个route

match ‘: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 { :controller =>photos, :action =>show, :id =>1, :user_id =>2}.

一个传入路径/photos/show/1?user_id=2将会被调度给Photos controllershow actionparams将会是{ :controller =>photos, :action =>show, :id =>1, :user_id =>2}

3.5 Defining Defaults默认定义

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

你不需要准确的使用:controller:action字符在一个route中。你可以默认的提供他们:

match ‘photos/:id’ => ‘photos#show’

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

通过这个routeRails将会匹配一个传入路径/photos/12PhotosControllershow action

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:

你同样也可以在route中定义其他的默认(设置)通过提供一个hash字典给:defaults选项。这甚至会应用于不需要指定参数作为动态分割。例如:

match ‘photos/:id’ => ‘photos#show’, :defaults => { :format => ‘jpg’ }

Rails would match photos/12 to the show action of PhotosController, and set params[:format] to “jpg”.

Rails将会匹配photos/12PhotosControllershow action,并且设置params[:format] to “jpg”

3.6 Naming Routes

You can specify a name for any route using the :as option.

你可以指定一个name给任何route使用:as选项。

match ‘exit’ => ‘sessions#destroy’, :as => :logout

This will create logout_path and logout_url as named helpers in your application. Calling logout_path will return /exit

这里将会在应用程序中创建logout_pathlogout_url作为(刚才)命名的routehelpers。调用logout_path将会返回/exit

3.7 HTTP Verb Constraints 限定HTTP 动作

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

你可以使用:via选项来限定请求一个或多个(HTTP)方法:

match ‘photos/show’ => ‘photos#show’, :via => :get

There is a shorthand version of this as well:

这里的短操作版本同样也是可以的:

get ‘photos/show’

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

你也可以运行超过一个动作到一个单独的route

match ‘photos/show’ => ‘photos#show’, :via => [:get, :post]

3.8 Segment Constraints分割限制

You can use the :constraints option to enforce a format for a dynamic segment:

你可以使用:constraints选项来强制一个动态分割的格式:

match ‘photos/:id’ => ‘photos#show’, :constraints => { :id => /[A-Z]\d{5}/ }

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

这个route将会匹配像这样的路径/photos/A12345。你可以使用这样的方式来更加简洁的表达相同的route

match ‘photos/:id’ => ‘photos#show’, :id => /[A-Z]\d{5}/

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

:constraints获取的正则表达式,其限定了正则表达式的锚不能被使用。例如下面的route将不会工作(使用了^锚指定从这里开始):

match ‘/:id’ => ‘posts#show’, :constraints => {:id => /^\d/}

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

然而,注意你不需要使用锚因为所有的routes锚定在开始位置。

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:

例如,下面的route将会允许poststo_param1-hello-world的值,其总是以一个数字和useruserto_param的值就像david)它从不以数字开始来share根名称空间。

match ‘/:id’ => ‘posts#show’, :constraints => { :id => /\d.+/ }

match ‘/:username’ => ‘users#show’

3.9 Request-Based Constraints Request-Based的限制

You can also constrain a route based on any method on the Request object that returns a String.

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

你也可以限制一个route 基于任何方法在Request对象时它都会返回一个String

你指定一个request-basedcontraint和你指定一个segment constaint是一样的。

match “photos”, :constraints => {:subdomain => “admin”}

You can also specify constraints in a block form:

你也可以指定限制在一个block form中:

namespace :admin do

constraints :subdomain => “admin” do

resources :photos

end

end

3.10 Advanced Constraints高级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:

如果你有一个更高级的contraint,你可以提供一个对象,Rails将会使用matches?回应这个对象。

让我来告诉你要想route所有的用户在一个黑名单中匹配(通过BlacklistControllermatches?方法)。你应该:

class BlacklistConstraint

def initialize

@ips = Blacklist.retrieve_ips

end

 

def matches?(request)

@ips.include?(request.remote_ip)

end

end

 

TwitterClone::Application.routes.draw do

match “*path” => “blacklist#index”,

:constraints => BlacklistConstraint.new

end

3.11 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

Route globbing是一种方式来指定特定的paramerter应该被一个route的其余的所有部分匹配。例如

match ‘photos/*other’ => ‘photos#unknown’

This route would match photos/12 or /photos/long/path/to/12, setting params[:other] to “12” or “long/path/to/12”.

这个route将会匹配photos/12或者/photos/long/path/to/12,设置params[:other] to “12”“long/path/to/12”

Wildcard segments can occur anywhere in a route. For example,

通配符分割可以发生在一个route的任何地方。例如,

match ‘books/*section/:title’ => ‘books#show’

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

将会匹配books/some/section/last-words-a-memoirparams[:section]等于“some/section”,以及params[:title]相当于“last-words-a-memoir”

Technically a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example,

从技术上讲一个route可以有甚至超过一个通配符的分割。matcher分配segments到参数是一个直观的方式。例如,

match ‘a/foo/b’ => ‘test#index’ # *a这一部分通配为a

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

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

match ‘*pages’ => ‘pages#show’

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:

match ‘*pages’ => ‘pages#show’, :format => false

If you want to make the format segment mandatory, so it cannot be omitted, you can supply :format => true like this:

match ‘*pages’ => ‘pages#show’, :format => true

3.12 Redirection

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

你可以重定向任何path到另一个path使用redirect helper在你的router

match “/stories” => redirect(“/posts”)

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

match “/stories/:name” => redirect(“/posts/%{name}”)

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

match “/stories/:name” => redirect {|params| “/posts/#{params[:name].pluralize}” }

match “/stories” => redirect {|p, req| “/posts/#{req.subdomain}” }

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.

3.13 Routing to Rack Applications

Instead of a String, like “posts#index”, which corresponds to the index action in the PostsController, you can specify any Rackapplication as the endpoint for a matcher.

match “/application.js” => Sprockets

As long as Sprockets responds to call and returns a [status, headers, body], the router won’t know the difference between the Rack application and an action.

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

3.14 Using root

You can specify what Rails should route “/” to with the root method:

root :to => ‘pages#main’

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.

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

4.1 Specifying a Controller to Use

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

resources :photos, :controller => “images”

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

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)
PUT /photos/:id update photo_path(:id)
DELETE /photos/:id destroy photo_path(:id)

Use photos_path, new_photo_path, etc. to generate paths for this resource.

4.2 Specifying Constraints

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

This declaration constraints 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.

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

constraints(:id => /[A-Z][A-Z][0-9]+/) do

resources :photos

resources :accounts

end

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

 

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.

4.3 Overriding the Named Helpers

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

resources :photos, :as => “images”

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.

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)
PUT /photos/:id update image_path(:id)
DELETE /photos/:id destroy image_path(:id)

4.4 Overriding the new and edit Segments重写newedit Segments

The :path_names option lets you override the automatically-generated “new” and “edit” segments in paths:

resources :photos, :path_names => { :new => ‘make’, :edit => ‘change’ }

This would cause the routing to recognize paths such as

/photos/make

/photos/1/change

The actual action names aren’t changed by this option. The two paths shown would still route to the new and edit actions.

 

If you find yourself wanting to change this option uniformly for all of your routes, you can use a scope.

scope :path_names => { :new => “make” } do

rest of your routes

end

4.5 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

scope “admin” do

resources :photos, :as => “admin_photos”

end

 

resources :photos

This will provide route helpers such as admin_photos_path, new_admin_photo_path etc.这将会提供比如 admin_photos_path, new_admin_photo_path等这样的route helpers

To prefix a group of route helpers, use :as with scope:

scope “admin”, :as => “admin” do

resources :photos, :accounts

end

 

resources :photos, :accounts

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

The namespace scope will automatically add :as as well as :module and :path prefixes.

You can prefix routes with a named parameter also:

scope “:username” do

resources :posts

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.

4.6 Restricting the Routes Created限制routes被创建

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:

默认的,Rails按照七种默认的actionindex, show, new, create, edit, update, and destroy)为你应用程序中的每个RESTful route创建routes

resources :photos, :only => [:index, :show]

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.

现在一个GET请求到/photos将会成功,但是一个POST/photos(其按理将会routecreate action)将会失败。

The :except option specifies a route or list of routes that Rails should not create:

resources :photos, :except => :destroy

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

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.

如果你的应用程序中有很多 RESTful routes,使用:only and :except来生成仅仅你实际需要的route能够消减内存使用和提速routing 进程。

4.7 Translated Paths翻译路径

Using scope, we can alter path names generated by resources:

使用scope,我们可以别名resources生成的路径name

scope(:path_names => { :new => “neu”, :edit => “bearbeiten” }) do

resources :categories, :path => “kategorien”

end

Rails now creates routes to the CategoriesController.

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)
PUT /kategorien/:id update category_path(:id)
DELETE /kategorien/:id destroy category_path(:id)

4.8 Overriding the Singular Form

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

如果你想定义一个单数形式的resource,你应该添加补充的rulesInflector

ActiveSupport::Inflector.inflections do |inflect|

inflect.irregular ‘tooth’, ‘teeth’

end

4.9 Using :as in Nested Resources在嵌套resources中使用:as

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

:as选项覆盖嵌套的resource自动生成的route的名字。例如:

resources :magazines do

resources :ads, :as => ‘periodical_ads’

end

This will create routing helpers such as magazine_periodical_ads_url and edit_magazine_periodical_ad_path.

5 Inspecting and Testing Routes检查和测试routes

Rails offers facilities for inspecting and testing your routes.

Rails提供设施来检查和测试你的routes

5.1 Seeing Existing Routes with rake使用rake来查看存在的routes

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:

如果你需要一个你应用程序中可用的完整的list,运行 rake routes命令。这将会打印所有你的routes(到终端),与routes.rb中出现的顺序一样。对于每个route,你将会看到:

  • The route name (if any)
  • The HTTP verb used (if the route doesn’t respond to all verbs)
  • The URL pattern to match 匹配的URL模式
  • The routing parameters for the route

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

          users GET  /users          {:controller=>"users", :action=>"index"}
formatted_users GET  /users.:format  {:controller=>"users", :action=>"index"}
                POST /users          {:controller=>"users", :action=>"create"}
                POST /users.:format  {:controller=>"users", :action=>"create"}

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

你可以限制列出的routes映射到一个别的controller设置 CONTROLLER环境变量:

$ CONTROLLER=users rake routes

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.

你会发现如果你扩大到你的终端不自动换行,来自rake routes会更具可读性。

5.2 Testing Routes

Routes should be included in your testing strategy策略 (just like the rest of your application). Rails offers three built-in assertions designed to make testing routes simpler:

  • assert_generates
  • assert_recognizes
  • assert_routing
5.2.1 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.

assert_generates断言是一个特别的设置选项生成一个特别的路径并且可以与默认的routes和定制的routes

assert_generates “/photos/1”, { :controller => “photos”, :action => “show”, :id => “1” }

assert_generates “/about”, :controller => “pages”, :action => “about”

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

assert_recognizesassert_generates的逆。它断言一个给定的path是被承认的并route到应用程序中的特定地点。

assert_recognizes({ :controller => “photos”, :action => “show”, :id => “1” }, “/photos/1”)

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

你可以提供一个:method参数来指定HTTP verbe

assert_recognizes({ :controller => “photos”, :action => “create” }, { :path => “photos”, :method => :post })

assert_recognizes({ :controller => “photos”, :action => “create” }, { :path => “photos”, :method => :post })

5.2.3 The assert_routing Assertion

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

断言 assert_routing检测route两方面:它测试访问路径生成选项,并且测试这个选项生成的路径。这样,它联合了 assert_generates and assert_recognizes的功能。

assert_routing({ :path => “photos”, :method => :post }, { :controller => “photos”, :action => “create” })

标签: guide http rails route ruby translate