Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to get the name of the previous action in controller

In rails I need to check the name of the previous method in controller. For example: There are methods A,B,C...etc; In a controller I want to execute a few statements only if it is coming from method A. How to write the condition for this? I have seen many links that says about the current action name and controller name but that was not what I needed. I need to get the name of the previous method. Thanks in advance.

like image 288
liya Avatar asked Mar 14 '14 11:03

liya


2 Answers

You can use this

url = Rails.application.routes.recognize_path(request.referrer)
last_controller = url[:controller]
last_action = url[:action]

src: https://stackoverflow.com/a/24189831/5063171

like image 200
El Fadel Anas Avatar answered Oct 19 '22 09:10

El Fadel Anas


You can use request.refererto get the HTTP referral header, which will be the previous visited URL.

However, this is not an ideal way of solving the problem you're faced with, as it's unreliable and will break if your URLs change. If you need to persist information about your user's path through the application, you could try storing variables in the session:

http://guides.rubyonrails.org/action_controller_overview.html#accessing-the-session

like image 20
Louis Simoneau Avatar answered Oct 19 '22 10:10

Louis Simoneau