Auditing: session[:user] reference in after_save callback

I know, it is against the MVC to speak directly to a session object in
the model but I am looking for a solution to this problem with auditing

I have a SystemLog model which works as a sort of auditor to track
changes. It has a user_id that references the user that initiated the
change and a text string with a description and some other columns.

Whenever I save a model, i want to create a SystemLog object with values
I can get from the model that is being saved itself, except for the
user_id.

How am I supposed to get the session[:user] data neatly to the model the
way Ruby wants it to? Or is there any other way to realise this auditing
process which I am overlooking?

The alternative violates the DRY philosophy. After every call to
@object.save in the controller I manually create a new SystemLog object
with the @object's attributes and session[:user] variable.

I'm probably mis-understanding the question, but is the problem you
want information about the user logged in? Could you not do a Find on
the user table using the ID of the user saved in the [:session] ?

Here's a solution by Pratik, although I have the feeling that he's, err,
somehow opposed to it. Just a gut feeling :slight_smile:

http://m.onkey.org/2007/10/17/how-to-access-session-cookies-params-request-in-model

Another solution mentioned in the first Rails Recipes book was to
(mis)use ActionController::Caching::Sweeping; because of their task,
Sweepers are observers that have access to the current controller. I
have yet to use them, but this approach seems to be quite clean to me.
Take a look at a comment by August Lilleaas in Pratiks article, he has
some example code for this.

HTH.

sw0rdfish wrote:

I'm probably mis-understanding the question, but is the problem you
want information about the user logged in? Could you not do a Find on
the user table using the ID of the user saved in the [:session] ?

On Apr 23, 5:01�pm, Chris Dekker <rails-mailing-l...@andreas-s.net>

Thats the plan yeah. But the thing is I want need the logged in user
(from the session in my MODEL, since this is the only place I can call
my before_ and after_save functions.

So the hard part is getting the ID from the session to the Model, since
this is not really Ruby's way of doing it.

Use an attr_accessor in your model.

attr_accessor :user_id
after_save :audit

def audit
  @systemlog = SystemLog.new
  @systemlog.user_id = self.user_id
end