简体   繁体   English

我如何从Rails中的url中猜出动作名称?

[英]How can I guess action name from url in Rails?

For example I have a url generated by something_path or something_url methods. 例如,我有一个由something_pathsomething_url方法生成的url 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. 您可以从终端/命令提示符运行rake routes ,以获取应用程序中所有路由的列表。 The output includes the HTTP method used, as well as the controller and action invoked. 输出包括使用的HTTP方法,以及调用的控制器和操作。

The routing system of Rails works two ways, it recognizes and builds URLs. Rails的路由系统有两种工作方式,它可以识别和构建URL。 You need the recognize_path method, like the following example shows: 您需要recogn_path方法,如下例所示:

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

Assuming that the URL was generated with something_path or something_url , it returns: 假设URL是使用something_pathsomething_url生成的,则返回:

{ :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 action_name可以访问处理操作
  • controller_name to get access to the processing controller controller_name可以访问处理控制器

In Rails 3: 在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"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Rails如何从模型中猜测表名? - How does Rails guess the table name from model? 在Rails中,如何从视图中输出动作的名称? - In Rails, how can you output the name of the action from inside the view? 为什么不能通过Devise 3和Rails 4为action_mailer.default_url_options设置主机名? - Why can't I set host name for action_mailer.default_url_options by Devise 3 and Rails 4? 反向铁路路由:从URL中查找操作名称 - Reverse rails routing: find the action name from the URL 运行Rails服务器时出错:您能猜出什么问题吗? 我该如何解决? - Error running rails server: can you guess what's wrong? How can I fix it? Rails-如何捕获指向我应用程序中当前操作的URL? - Rails - how can I capture the URL that directed to the current action in my app? 如何调用动作,从js传递值到该动作并在Rails 3的页面上重新呈现js? - How can I call an action, pass a value to the action from js and re-render the js on a page in rails 3? 如何在Rails中对change进行操作? - how can I make an action onchange in Rails? Rails:如何优化此操作 - Rails: how can I optimize this action 如何使用domain.name设置'config.action_mailer.default_url_options'的值? - How can I set the value of 'config.action_mailer.default_url_options' with domain.name?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM