Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse rails routing: find the action name from the URL

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?

like image 544
SooDesuNe Avatar asked Aug 14 '10 02:08

SooDesuNe


2 Answers

With Rails 3 you can do:

Rails.application.routes.recognize_path('/areas/1')
 => {:controller=>"areas", :action=>"show", :id=>"1"} 
like image 113
Jacob Atzen Avatar answered Nov 02 '22 03:11

Jacob Atzen


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!

like image 25
Geoff Lanotte Avatar answered Nov 02 '22 03:11

Geoff Lanotte