开发者

Basic rails 3 routes and unknown routes (including wildcards)

I've been reading about routing in Rails 3 and have been unsuccessful in achieving what I need. Still fairly new to routes in Rails 3 so I may simply be overlooking things or overcomplicating it.

This is what I'm looking to achieve:

website/foo routes to the foo controller, index action

website/foo/index routes to the foo controller, index action

website/foo/bar routes to the foo controller, bar action

website/foo/random routes to the foo controller, index action

website/foo/bar/rondom routes to the foo controller, bar action

where "random" can be any text, numbers, paths (/new/x/w/y/23) or whatever.

I tried using both match, and resources with collection and while it handled the base case, it did not handle "random".

I'm also looking for the respective named path, should that be specified or wi开发者_StackOverflowll it be generated?


You are looking for route globbing.

foo/bar/*additional => "foo#bar" 

Examples:

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/"


http://guides.rubyonrails.org/routing.html contains heaps of really useful information, especially the section on route globbing.

To match exactly what you defined above you could:

# 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

You can use the :as option to specify a named route, e.g.

match 'foo' => 'foo#index', as: 'foo' # helper would be website_foo_path
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜