`

在Rails中的 Model中使用current_user

阅读更多
在Rails中的 Model(业务层)中使用current_user,关于这个话题我google了一下,看到了有两种方式:
第一种就是为某一个Model加一个类变量current_user,然后在控制层(Controller)中加一个前置过滤器,来设置Model的current_user类变量。

代码如下:
在Model中
class User < ActiveRecord::Base
  cattr_accessor :current_user
  #...
end


在控制器中:
class ApplicationController < ActionController::Base
  include AuthenticatedSystem
  before_filter :set_current_user

  protected
  def set_current_user
    User.current_user = current_user # current_user方法已经在lib中写好了
  end
end


第二种比较特别\trick,是在线程中加一个变量,代码如下:
在ApplicationController中
class ApplicationController < ActionController::Base

before_filter :set_request_environment

private

# stores parameters for current request

def set_request_environment

User.current = current_user # current_user is set by restful_authentication
# You would also set the time zone for Rails time zone support here:
# Time.zone = Person.current.time_zone

end


在Model中:
class User < ActiveRecord::Base

  #-----------------------------------------------------------------------------------------------------
  # CLASS METHODS
  #-----------------------------------------------------------------------------------------------------

  def self.current
    Thread.current[:user]
  end

  def self.current=(user)
    raise(ArgumentError,
        "Invalid user. Expected an object of class 'User', got #{user.inspect}") unless user.is_a?(User)
    Thread.current[:user] = user
  end

end


大家 认为哪一种方式更好呢? 我个人比较看好第二种。



相关链接:
http://clearcove.ca/blog/2008/08/recipe-make-request-environment-available-to-models-in-rails/#more-273

http://www.neeraj.name/blog/articles/755-using-current_user-in-model-and-other-places
分享到:
评论
4 楼 darkbaby123 2010-01-28  
个人觉得,原作者没有把current_user放到Model层是有道理的。所谓当前用户只是针对会话而言,放在Controller层正合适,而Model层只处理和模型相关的逻辑,它是可以独立存在的。这样也方便在console中调用,或者写单元测试。
所以为什么不直接传参呢?
3 楼 Hooopo 2009-12-25  
yangzhihuan 写道
窃以为,要在model中使用current_user的话,最好的办法是传递变量.

另外,我觉得可以尽量把跟user相关的方法写在User类中,在有需要使用到current_user的时候,直接current_user.method(),岂不是更好?

偶早就和他这么说过...他就是不信。。。
2 楼 yangzhihuan 2009-12-24  
窃以为,要在model中使用current_user的话,最好的办法是传递变量.

另外,我觉得可以尽量把跟user相关的方法写在User类中,在有需要使用到current_user的时候,直接current_user.method(),岂不是更好?
1 楼 Hooopo 2009-12-24  
都不好,还是别把current user放在model里好

相关推荐

Global site tag (gtag.js) - Google Analytics