开发者

How to pass a default query param with Rails 2.3.x routing

I'm trying to do something trivial. I have a bunch of URLs that I need to map like the following:

http://example.com/foo

http://example.com/foo/somethin开发者_如何学Gog

Both need to go to the same controller/action. The problem I'm having is when http://example.com/foo is invoked, I need to specify a default query parameter. I thought that's what the :defaults hash does in routes.rb, but unfortunately the following doesn't work:

map.connect 'foo', :controller => 'something', :action => 'anaction', 
  :defaults => { :myparam => 'foobar' }

This should route http://example.com/foo to the something controller, anaction action, and make params[:myparam] point to the string "foobar".

I'm assuming for the second example http://example.com/foo/something, I'll need an additional route.

What's the best way to tackle this?


I wouldn't complicate things by adding such logic to my routes file, I'd just do it in my action:

params[:my_param] ||= 'foobar'


Untested, but:

map.connect 'foo', :controller => 'something', :action => 'anaction', :myparam => 'foobar'

It looks like the :controller and :action arguments in there are not in any way special, but just end up feeding into params. The 2.3.8 documentation seems to confirm this.

More formally, you can include arbitrary parameters in the route, thus:

map.connect ':controller/:action/:id', :action => 'show', :page => 'Dashboard'

This will pass the :page parameter to all incoming requests that match this route.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜