在Rails中的 Model中使用current_user

[b]在Rails中的 Model(业务层)中使用current_user[/b],关于这个话题我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


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


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

[url]http://www.neeraj.name/blog/articles/755-using-current_user-in-model-and-other-places[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值