我一直在阅读Rails 3中的路由,并且未能成功实现我的需求。对于Rails 3中的路由来说还是比较新的,所以我可能只是忽略了一些东西或者使它过于复杂。
这是我想要实现的目标:
website/foo
路由到foo
控制器,index
操作
website/foo/index
路由到foo
控制器,index
操作
website/foo/bar
路由到foo
控制器,bar
操作
website/foo/random
路由到foo
控制器,index
操作
website/foo/bar/rondom
路由到foo
控制器,bar
操作
其中“random”可以是任何文本,数字,路径(/ new / x / w / y / 23)或其他。
我尝试将match
和resources
与collection
同时使用,并且在处理基本情况时,它没有处理“随机”。
我也在寻找相应的命名路径,是否应该指定或是否会生成?
答案 0 :(得分:1)
您正在寻找route globbing。
foo/bar/*additional => "foo#bar"
示例:
website/foo/bar/random # params[:additional] = "random"
website/foo/bar/random/2 # params[:additional] = "random/2"
website/foo/bar/random/and/more/1/random/stuff/ # params[:additional] = "random/and/more/1/random/stuff/"
答案 1 :(得分:1)
http://guides.rubyonrails.org/routing.html包含大量非常有用的信息,尤其是关于route globbing的部分。
要完全匹配您在上面定义的内容,您可以:
# config/routes.rb
namespace :website do
match 'foo' => 'foo#index'
match 'foo/index' => 'foo#index'
match 'foo/bar' => 'foo#bar'
match 'foo/*random' => 'foo#index' # params[:random] will contain "hello/world" if the URL is /website/foo/hello/world
match 'foo/bar/*random' => 'foo#bar'
end
您可以使用:as
选项指定命名路由,例如
match 'foo' => 'foo#index', as: 'foo' # helper would be website_foo_path