简体   繁体   中英

How can I guess action name from url in Rails?

For example I have a url generated by something_path or something_url methods. I need to know action name from that url .

You don't need to guess. You can run rake routes from the Terminal/Command Prompt to get a list of all the routes in your application. The output includes the HTTP method used, as well as the controller and action invoked.

The routing system of Rails works two ways, it recognizes and builds URLs. You need the recognize_path method, like the following example shows:

ActionController::Routing::Routes.recognize_path('/mycontroller/myaction', :method => :get)

Assuming that the URL was generated with something_path or something_url , it returns:

{ :action => 'myaction', :controller => 'mycontroller' }

From which you are able to extract the action part.

If you are in a view, you can use

  • action_name to get access to the processing action
  • controller_name to get access to the processing controller

In Rails 3:

Rails.application.routes.recognize_path("http://example.ltd/registrants")
=> => {:action=>"index", :controller=>"registrants"}

If you're in an engine, Events

Events::Engine.routes.recognize_path("/registrants")
=> {:action=>"index", :controller=>"events/registrants"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM