'Identify which action is being called inside a model. Ruby on Rails
How do I come to know whether a create or any other action has been called from inside a model. Basically I am doing database logging and want to track whether a create or other actions are being performed.
For doing the logging part I am using the concept of ActiveRecord::Observer. But there I am not able to find out whether the user is creating or doing something else. So please tell me some way that rails provides us to identify the action inside the model.
thanks in advance.
Solution 1:[1]
Such this kind of tracking should be performed on the Controller. Observers are only model-aware and should be model-aware only.
Consider the case where you are updating the object from the console. The observer will be triggered, but you have no request context here.
Solution 2:[2]
Which ever action is called in application is stored in params[:action] and params is not accessible in models. So i don't think you can see which action is getting called from models.
Thanks,Anubhaw
Solution 3:[3]
This is not recommended from architectural point of view but this is used only for low level logging deep inside Model and doesn't do any harm. Also this is thread-safe solution.
ApplicationController or just single controller:
around_filter :store_remote_ip_in_thread
def store_remote_ip_in_thread
begin
Thread.current[:remote_ip] = request.remote_ip
yield
ensure
Thread.current.delete :remote_ip
end
end
Reusable module for retrieval:
module RemoteIpAware
def current_remote_ip
Thread.current[:remote_ip] || '-'
end
end
Somewhere in model/mailer/lib class:
include RemoteIpAware
...
#use current_remote_ip method anywhere
Keep in mind I wrote it from my memory.. syntax may not be ok ;) In you case instead of remote IP you can save params[:action] :controller name etc..
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Simone Carletti |
| Solution 2 | Anubhaw |
| Solution 3 | gertas |
