方法如下:
module ActiveRecordExtension
def current_passport
Thread.current[:passport]
end
def current_passport=(value)
Thread.current[:passport] = value
end
def puts_sth
puts ActiveRecordExtension.current_passport.username
end
module_function :current_passport, :current_passport=
end
ActiveRecord::Base.send :include, ActiveRecordExtension
Fetch current user in models:
https://rails-bestpractices.com/posts/2010/08/23/fetch-current-user-in-models
最后大概是这个样子:
module ActiveRecordExtension
class << self
attr_accessor :current_passport
end
def puts_sth
puts ActiveRecordExtension.current_passport.username
end
end
ActiveRecord::Base.send :include, ActiveRecordExtension
controller 中添加 before_action :set_current_passport
def set_current_passport
ActiveRecordExtension.current_passport = current_passport
end
感谢各位大神的帮助。
改成这个样子就可以了:
module ActiveRecordExtension
def current_passport
Thread.current[:passport]
end
def current_passport=(value)
Thread.current[:passport] = value
end
def puts_sth
puts ActiveRecordExtension.current_passport.username
end
module_function :current_passport, :current_passport=
end
ActiveRecord::Base.send :include, ActiveRecordExtension
7 楼才是正解,少年
原理也是 Thread.current,不过在 Request 进来时设置,Request 完成时清除!这是关键!具体可以看那个 gem 都代码!少年