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.
Asked
Active
Viewed 8,019 times
7
-
1Each requests from different actions are independent. If you really want to transfer this kind of data between requests, maybe session is a place to store. – Sibevin Wang Mar 14 '14 at 11:32
-
But I don't need those values throughout the session. Here I just want to know from which action it is coming. Actually I am new to rails. – liya Mar 14 '14 at 11:46
-
HTTP is stateless, so if your controller wants to know what action came before that information has to come from somewhere. It can come from HTTP headers (using request.referer) or it can be stored in the session or in a cookie between requests, or you could append an extra query string parameter. – Louis Simoneau Mar 14 '14 at 11:47
-
1It might help if we knew your end goal. – DickieBoy Mar 14 '14 at 12:08
-
1This seems like an X/Y problem http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – sevenseacat Mar 25 '14 at 08:29
2 Answers
14
You can use this
url = Rails.application.routes.recognize_path(request.referrer)
last_controller = url[:controller]
last_action = url[:action]

El Fadel Anas
- 1,581
- 2
- 18
- 25
12
You can use request.referer
to 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

Louis Simoneau
- 1,781
- 14
- 18
-
But is there any way to know the previous method? `request.referer` gives me the full url `http://localhost:3000/example/index/1` I need to get only `/example/index` – liya Apr 07 '14 at 06:22
-
1As per this answer http://stackoverflow.com/questions/3481731/reverse-rails-routing-find-the-the-action-name-from-the-url you could do a reverse lookup on the URL to get the controller and action. But again, that's a bit hacky and fragile. If your app depends on tracking state across multiple requests, it should explicitly do so by persisting that information, either in a cookie, in a session, or in the database. – Louis Simoneau Apr 07 '14 at 06:25