Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 967
Chloe Avatar asked Jan 13 '16 20:01

Chloe


People also ask

How do I find my current controller?

If you require to get current controller name in your view file or in your middleware or your serviceprovider etc. you can get your controller details from current route like UserController, HomeController ect. you can also get full path of controller file.

How do I return specific view on a controller?

To return a view from the controller action method, we can use View() method by passing respective parameters. return View(“ViewName”) – returns the view name specified in the current view folder (view extension name “. cshtml” is not required. return View("~/Views/Account/Register.

What is action method in controller?

An action (or action method ) is a method on a controller that handles incoming requests. Controllers provide a logical means of grouping similar actions together, allowing common sets of rules (e.g. routing, caching, authorization) to be applied collectively. Incoming requests are mapped to actions through routing.


2 Answers

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

like image 185
Vasfed Avatar answered Sep 28 '22 10:09

Vasfed


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

like image 32
Tilo Avatar answered Sep 28 '22 11:09

Tilo