Rails3.2 Match路由

浏览:727 发布日期:2016-04-29 14:58:50

Rails 3.2 Match路由

match(path, options = nil)

匹配一个网址模式到一个或多个路由。在一个模式中的任意符号被解释为URL查询参数,从而可以在动作中使用这些参数。

# sets :controller, :action and :id in params
match ':controller/:action/:id'

:controller, :action这两个符号很特别,它们分别映射到控制器与动作。模式还可以使用通配符。

match 'songs/*category/:title' => 'songs#show'

# 'songs/rock/classic/stairway-to-heaven' sets
#  params[:category] = 'rock/classic'
#  params[:title] = 'stairway-to-heaven'

当路由模式指向内部路由时,在routes中:action和:controller应该被设置到options中,或提供一个Hash。例如:

match 'photos/:id' => 'photos#show'
match 'photos/:id', :to => 'photos#show'
match 'photos/:id', :controller => 'photos', :action => 'show'

一个路由匹配同样可以指向一个Rack节点,以及所有正确相应call方法的:

match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon"] }
match 'photos/:id' => PhotoRackApp
# Yes, controller actions are just rack endpoints
match 'photos/:id' => PhotosController.action(:show)

Options

如果使用options参数,就没有必要再提供url了。如果提供了path属性,又提供options选项,那么path的:controller, :action会覆盖options中的选项。

:controller 路由的控制器

:action 路由的动作

:path 路由的路径前缀。

match :controller => 'admin', :action => 'show2', :path => "dd"

这将会匹配 /dd,来访问admin#show2

:module 指定:controller的命名空间

match :module => 'sekret', :controller => 'posts', :action => "a", :path => "aa"
#=> Sekret::PostsController#a

:as 用于生成路由帮助方法。将会生成 namepath, nameurl两个帮助方法,

:via 允许的HTTP动词。

match 'path' => 'c#a', :via => :get
match 'path' => 'c#a', :via => [:get, :post]

:to 指向一个Rack节点。可以是一个相应call回调的对象,或是一个代表控制器与动作的字符串。

match 'path', :to => 'controller#action'
match 'path', :to => lambda { |env| [200, {}, "Success!"] }
match 'path', :to => RackApp

:on 包装一个RESTful的上下文。可用的值包括:member, :collection和:new.它只在resource(s)块中使用。例如:

resource :bar do 
      match 'foo' => 'c#a', :on => :member, :via => [:get, :post]
end

这里在resource :bar中添加一个支持:get, :post动词的foo成员路由,

通过:on => :collect或collect块,指定一个集合路由,例如:

resources :photos do
  collection do
    get 'search'
  end
end

resources :photos do
  get 'search', on: :collection
end

这段路由能识别/photos/search是个GET请求,将映射到search动作中,同时还会生成searchphotosurl和searchphotospath两个帮助方法。

通过指定 on: :new,可以添加额外的新建动作。

resources :comments do get 'preview', on: :new end

它能够相应/comments/new/preview是个GET请求。

:constraints 约束参数,可以指定一个正则表达式,或是一个实现了mathes?方法的对象。

match 'path/:id', :constraints => { :id => /[A-Z]\d{5}/ }

class Blacklist
  def matches?(request) request.remote_ip == '1.2.3.4' end
end
match 'path' => 'c#a', :constraints => Blacklist.new

:default 设置参数的默认值。

# Sets params[:format] to 'jpg' by default
match 'path' => 'c#a', :defaults => { :format => 'jpg' }

:anchor 锚定一个匹配模式。默认为true。当设置为false,将匹配所有以'path'开始的请求。

# Matches any request starting with 'path'
match 'path' => 'c#a', :anchor => false