问题
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.
回答1:
You can use a before_save to trigger an event when the model is saved. To determine if it is a save or a create you have this method new_record? which will tell you if it's a new instance or not. You can also know which attributes have changed
回答2:
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.
回答3:
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
回答4:
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..
来源:https://stackoverflow.com/questions/3726136/identify-which-action-is-being-called-inside-a-model-ruby-on-rails