Chloe
Chloe

Reputation: 26264

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'

Upvotes: 27

Views: 23657

Answers (4)

Kaka Ruto
Kaka Ruto

Reputation: 5125

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.

Upvotes: 0

Chloe
Chloe

Reputation: 26264

This worked.

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

Upvotes: 1

Vasfed
Vasfed

Reputation: 18444

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

Upvotes: 38

Tilo
Tilo

Reputation: 33722

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

Upvotes: 4

Related Questions