23

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'
2
  • action_name gives you the current action name
    – Joel
    Jan 13, 2016 at 20:21
  • @Joel #action_name is not even a method in Rails. api.rubyonrails.org
    – Chloe
    Jan 13, 2016 at 20:21

4 Answers 4

32

Controllers have action_name method/accessor (defined in AbstractController::Base for current rails, ActionController::Base for older)

5
3

you can use __method__ to get to the name of the current method.

e.g

 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:

params[:controller]
params[:action]

In a view, you can access action_name

2
  • It's in a before_filter. I don't want the current method.
    – Chloe
    Jan 13, 2016 at 20:25
  • 1
    I added to my answer
    – Tilo
    Jan 13, 2016 at 20:34
1

This worked.

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

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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.