开发者

In Ruby on Rails, the :id is only optional in routes.rb? How to tell optional vs not optional?

In routes.rb

  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'

but then

http://localhost:3000/foobars/alt
开发者_如何学编程

will work too. The params are:

{"action"=>"alt", "controller"=>"foobars"} 

so looks like :id is optional here. How can you tell it is optional vs not optional? Can you make it so that it is not optional in routes.rb?


You can use :requirements to impose some conditions on :id for the route to match, ie: map.connect ':controller/:action/:id', :requirements => { :id => /\d{4}/ } . That way, if :id doesn't match the requirement, the route won't match either.


In the controller, you should just give an error if params[:id] is nil.


http://localhost:3000/foobars/alt

To achieve this path you have to mention this route in routes.rb.

something like following

map.resources :foobars, :collection=> {:alt=>:get }

otherwise it will treat alt as params[:id] and if you create controller using scaffolding it will go to the show action of your foobars controller.

So for above mention url it becomes optional and treat it as an action insetad of params[:id]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜