I understand how to turn :controller
, :action,
:etc
into a URL. I'm looking to do the reverse, how can the action that the rails router will call be found from the URL?
views:
56answers:
1
+1
A:
someone else might have a shorter way to do this, but if you are just evaluating a URL, then you go to the ActionController::Routing::RouteSet
class
for a config.routes.rb
map.resources :sessions
the code to find is:
ActionController::Routing::Routes.recognize_path('/sessions/new', {:method => :get})
#=> {:controller => 'sessions', :action => 'new'}
Right:
ActionController::Routing::Routes.recognize_path('/sessions/1/edit', {:method => :get})
#=> {:controller => 'sessions', :action => 'edit', :id => 1}
Wrong - without the method
being explicitly added, it will default match to /:controller/:action/:id
:
ActionController::Routing::Routes.recognize_path('/sessions/1/edit')
#=> {:controller => 'sessions', :action => '1', :id => 'edit'}
If you are within the action and would like to know, it is quite a bit easier by calling params[:action]
everything you ever wanted to know about routeset can be found here: http://caboo.se/doc//classes/ActionController/Routing/RouteSet.html#M004878
Hope this helps!
Geoff Lanotte
2010-08-14 02:45:11
I like your idea. Why does: route_set.recognize_path(app.edit_foo_path(1))return: {:controller=>"foos", :action=>"1", :id=>"edit"}Certanly, rails knows that the action is edit, and the id is 1, not vise-versa?
SooDesuNe
2010-08-14 04:13:25
it appears to be matching on `/controller/action/id` instead of the RESTful route. Testing, I was able to get it to work properly by always passing the method, without the method - it always goes to default. I also edited the post, you want to use 'ActionController::Routing::Routes' instead.
Geoff Lanotte
2010-08-14 04:55:36