Thursday, November 7, 2013

Get the controller object in model rails

My Site require a audit trail functionality who did activity, what are changes he made, from which ip address and lot more details. So i written the after_create, after_update, and after_destroy ActiveRecord callback in the ActiveRecord::Base class. It solves my purpose but i need who did it, from which ip he did it.

So i added a before filter in application controller which add the controller instance to current thread,

 Thread.current.thread_variable_set('controller', self)

As in the same thread the operation happening on the ActiveRecord.

So i can get back the controller instance and call the current_user method on it

Thread.current.thread_variable_get('controller').current_user

now i have to make my current_user method public and to avoid it calling from browser as action i have to hide it by

hide_action :current_user

No comments: