Rails 3 设计,current_user 在模型中不可访问? [英] Rails 3 devise, current_user is not accessible in a Model ?
问题描述
在我的 project.rb 模型中,我正在尝试使用动态变量创建范围:
in my project.rb model, I'm trying to create a scope with a dynamic variable:
scope :instanceprojects, lambda {
where("projects.instance_id = ?", current_user.instance_id)
}
我收到以下错误:
undefined local variable or method `current_user' for #<Class:0x102fe3af0>
我可以在控制器的哪个位置访问 current_user.instance_id
... 模型是否有无法访问它的原因以及获得访问权限的方法?另外,这是创建上述范围的正确位置,还是属于控制器?
Where in the controller I can access current_user.instance_id
... Is there a reason the model can't access it and a way to get access? Also, is this the right place to create a scope like the above, or does that belong in the controller?
推荐答案
正如您已经指出的那样,这没有多大意义.current_user 根本不属于模型逻辑,应该在控制器层面处理.
This doesn't make much sense, as you already pointed. The current_user doesn't belong to model logic at all, it should be handled on the controller level.
但是你仍然可以像这样创建范围,只需从控制器传递参数给它:
But you can still create scope like that, just pass the parameter to it from the controller:
scope :instanceprojects, lambda { |user|
where("projects.instance_id = ?", user.instance_id)
}
现在你可以在控制器中调用它了:
Now you can call it in the controller:
Model.instanceprojects(current_user)
这篇关于Rails 3 设计,current_user 在模型中不可访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!