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?
Asked
Active
Viewed 5,699 times
16
2 Answers
27
With Rails 3 you can do:
Rails.application.routes.recognize_path('/areas/1')
=> {:controller=>"areas", :action=>"show", :id=>"1"}

Jacob Atzen
- 559
- 1
- 4
- 5
13
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
- 7,490
- 1
- 38
- 50
-
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 Aug 14 '10 at 04:13
-
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 Aug 14 '10 at 04:55