[Rails] usermonitor / user stamping active record

Ezra Zygmuntowicz
2006-07-18T17:21:56Z

On Jul 18, 2006, at 8:18 AM, Oliver Robinson wrote:

> Quick question about userstamping records in a similar way to
> timestamping.  There is an example of how this might work at:
>
> http://wiki.rubyonrails.org/rails/pages/Howto+Add+created_by+and
> +updated_by/versions/7
>
> This seems to work fine on my development system.  However, I am not
> sure how the User.current_user method, which is required, can
> guarantee
> to return the correct user since this is a static accessor/method.
> If I
> set the class-level current_user as part of my request processing,
> then
> so long as no other requests come in in the mean time, all well and
> good.  however, if some other request is made by a different user
> between me setting the current user and saving the record, then
> presumably the record will be stamped with the other user.
>
> Is there something special about class scope within rails, i.e. is it
> scoped per request?  Otherwise, what is the correct way to go about
> this?
>
> I''m no great Ruby expert, but have been using it for a while.
>
> Ta


The trick to making this thing work reliably is to make sure that you
set the current_user on each and every request. Rails instantiates a
new object from your classes on each request. SO as long as you have
a before_filter that sets the current use like in the above examples
then it will not get affected byt other requests. You can count on
that class variable accessor to do the right thing as long as you set
it on each and every request.

-Ezra