简体   繁体   English

如何从控制器中获取当前操作?

[英]How do I get the current action from within a controller?

How do I get the current action from within a controller? 如何从控制器中获取当前操作? current_page? works for views, but not controllers. 适用于视图,但不适用于控制器。

redirect_to step3_users_path unless current_page?(step3_users_path)

I also tried 我也试过了

controller.action_name == 'step3'

I also tried 我也试过了

params[:action_name] == 'step3'

控制器具有action_name方法/访问器(在AbstractController::Base为当前rails定义, ActionController::Base为旧版本)

you can use __method__ to get to the name of the current method. 您可以使用__method__来获取当前方法的名称。

eg 例如

 def Klass
   def method1
     puts __method__
   end
 end

 > k = Klass.new
 > k.method1
 => :method1

Once the request goes through Rails, you will be able to access this in the Controller: 一旦请求通过Rails,您就可以在Controller中访问它:

params[:controller]
params[:action]

In a view, you can access action_name 在视图中,您可以访问action_name

This worked. 这很有效。

logger.debug params
redirect_to step3_users_path unless params[:action] == 'step3'

A simple way to get started is to set a breakpoint somewhere within your code where your action is running. 一种简单的入门方法是在代码中的某个位置设置一个断点,在该位置运行您的操作。

If you are using pry , do so with binding.pry , then you can list all params that are being passed by that action by writing params into the console and pressing enter. 如果您正在使用pry ,请使用binding.pry执行此操作,然后您可以通过将params写入控制台并按Enter键来列出该操作传递的所有参数。

Once you get the name of the param, then get it by using, for example params[:action] , to get the name of the controller action. 获得param的名称后,通过使用params[:action]来获取它,以获取控制器操作的名称。

暂无
暂无

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

相关问题 如何从控制器动作中调用另一个控制器动作? - How do I call another controller action from within a controller action? 如何从其控制器内部调用动作,以便其过滤器也被隐式调用? - How do I call an action from within its controller such that its filters are also called implicitly? 如何从控制器动作中向Rails动态添加after过滤器? - How do I dynamically add an after filter to Rails from within a controller action? 如何从Rails的控制器中访问路由信息(HTTP动词,动作名称等)? - How do I access the route information (HTTP verb, action name, etc . . .) from within a controller in Rails? 如何获得链接以执行正确的控制器操作? - How do I get my link to hit the correct controller action? 如何获得链接到嵌套控制器的destroy动作的链接? - How do I get a link_to the destroy action of a nested controller? 在Rails 3中,如何获取控制器的“ index”动作的路径? - In Rails 3, how do I get the path of a controller's `index` action? 如何获取Rails应用程序的URL,而不是当前控制器的URL - How do I get the URL of a rails app…not the current controller URL Rails - 如何避免必须从另一个控制器中的create action触发一个控制器中的create操作 - Rails - how do I avoid having to trigger the create action in one controller from the create action in another controller 如何在不离开当前控制器的情况下从另一个控制器执行操作 - How to execute an action from another controller without leaving the current controller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM