[英]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.