在Rails 3上所有者过滤的模型对象 [英] Owner-filtered model objects on Rails 3
问题描述
我需要对ActiveRecord模型进行一些过滤,我想按owner_id过滤所有模型对象.我需要的基本上是ActiveRecord的default_scope.
I need to do some filtering on my ActiveRecord models, I want to filter all my model objects by owner_id. The thing I need is basically the default_scope for ActiveRecord.
但是我需要通过一个会话变量进行过滤,该变量无法从模型中访问.我已经阅读了一些解决方案,但是没有一个可行的方法,基本上任何一个都说你声明default_scope时可以使用会话.
But I need to filter by a session variable, which is not accessible from the model. I've read some solutions, but none works, basically any of them says that you can use session when declaring default_scope.
这是我对范围的声明:
class MyModel < ActiveRecord::Base
default_scope { where(:owner_id => session[:user_id]) }
...
end
简单,对吧?但是它不能说方法会话不存在.
Simple, right?. But it fails saying that method session does not exists.
希望可以为您提供帮助
推荐答案
模型中的会话对象被认为是不好的做法,相反,您应该向User
类中添加一个类属性,该属性是在around_filter
中设置的您的ApplicationController
,基于current_user
Session objects in the Model are considered bad practice, instead you should add a class attribute to the User
class, which you set in an around_filter
in your ApplicationController
, based on the current_user
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
中,您可以执行以下操作:
And now in your MyModel
you can do the following:
default_scope where( owner_id: User.current_id ) #notice you access the current_id as a class attribute
这篇关于在Rails 3上所有者过滤的模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!