开发者

Rails: accessing current user session in a model (

Maintaining a Rails v2.3.8 app deployed on Apache with mod_passenger.

I need access to current user session in one of the models (an Auditor observer to be exact). I know this breaks the MVC principle. But i have to violate it as I have an observer that needs to know the currently logged in user. I have a lot of controllers and placing the call to Auditor logger would not be very DRY.

I'm just trying to be able to call User.current with currently logged in user session returned. However I've ran into an issue with caching/thread-safety. The original author used a class variable (@@current) to store the current user. But this is not thread safe, so I turned it into this

class User < AR:Base
  ...
  def self.current
    Thread.current[:user]
  end

  def self.current=(user)
    Thread.current[:user] = user
  end
  ...
end

So it should be thread-safe. And in Auditor observer I have a call:

Auditor(subject, action, object)

Where I pass in User.current as subject.

This code works great in development, but in productions I get incorrect values from User.current. At开发者_运维问答 times I get another logged in user's record and not the current one. So there is some thread-safety/class-caching issue that still exists, but I can't figure out how to fix it.

Any suggestions? Thanks


ActiveRecord and ActionPack are completely different so you do not have access to session/cookies in models. If you need the current user you have two options.

Option 1 - Pass the current user to the model

In your controller:

def index
    Audit.get_current_user(current_user)
    #where audit is your model that you will send the current_user to
end 

Option 2 - Have a user model that performs action after a user object is modified.

In your user model:

before_save :adjust_user

def adjust_user
    #self will be the object that was just modified aka the current user
end 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜