Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Get the controller and action name based on a path

I am trying to get the controller and action name based on a path. I have a route:

map.resources :permissions

I thought that I could use:

ActionController::Routing::Routes.recognize_path "/permissions/1"

To get a hash like:

{ :controller => "permissions", :action => "show" }

The actual hash that comes back is:

{ :controller => "permissions", :action => "1" }

How do I get the correct action name instead of just my passed in ID? The dispatcher must be able to get at it somehow or Rails wouldn't work, but I am having trouble locating how it is accomplished.


2 Answers

As of Rails 4 the method to recognize the path is now Rails.application.routes.recognize_path as opposed to ActionController::Routing::Routes.recognize_path and it returns a hash of controller, action, and id like so:

Rails.application.routes.recognize_path(app.edit_somecontroller_path(1))
 => {:controller=>"somecontroller", :action=>"edit", :id=>"1"}
like image 147
Fred Willmore Avatar answered Sep 14 '25 17:09

Fred Willmore


What are you really after? If you're really after the action name and controller name... you can just ask for

controller.controller_name

and

controller.action_name

Does that help, or do you really need to parse a string to do it?

like image 39
mylescarrick Avatar answered Sep 14 '25 18:09

mylescarrick