模型中的会话对象被认为是不好的做法,相反,您应该根据 current_user 向您在 中User
设置的类添加一个类属性around_filter
ApplicationController
class User < ActiveRecord::Base
#same as below, but not thread safe
cattr_accessible :current_id
#OR
#this is thread safe
def self.current_id=(id)
Thread.current[:client_id] = id
end
def self.current_id
Thread.current[:client_id]
end
end
在你ApplicationController
做的:
class ApplicationController < ActionController::Base
around_filter :scope_current_user
def :scope_current_user
User.current_id = current_user.id
yield
ensure
#avoids issues when an exception is raised, to clear the current_id
User.current_id = nil
end
end
现在MyModel
您可以执行以下操作:
default_scope where( owner_id: User.current_id ) #notice you access the current_id as a class attribute