如何访问模型中的 current_user 对象? [英] How to access current_user object in model?
问题描述
我正在尝试在我的团队"模型中编写一个方法,但 current_user 显示此错误
I am trying to write a method in my "team" model but current_user is showing this error
未定义的局部变量或方法 `current_user' for #
undefined local variable or method `current_user' for #
def set_default_url
if current_user.id == self.user_id
"/assets/default_black_:style_logo.jpg"
else
"/assets/default_:style_logo.jpg"
end
end
current_user 方法适用于其他模型和控制器.我是这样调用这个方法的.
The method current_user is working fine for other models and controllers . I am calling this method like this .
has_attached_file :logo, :styles => {
:medium => "200x200#",
:thumb => "100x100#",
:small => "50x50#"
},
:default_url => :set_default_url
我正在使用 rails 3.2 、 ruby 1.9.3 和 devise 3.1 .这似乎是一项简单的任务,但我不明白错误在哪里.如果有人在这里帮助我,我将非常感激.
I am using rails 3.2 , ruby 1.9.3 and devise 3.1 . It seems to be simple task but I don't understand where the fault lies . I will be really thankful if someone helps me out here .
推荐答案
current_user
is not available in any model, to access current_user
in model do this
current_user
is not available in any model, to access current_user
in model do this
在您的应用程序控制器中
In your application controller
before_filter :set_current_user
def set_current_user
Team.current_user = current_user
end
在您的 Team
模型中添加此行
in your Team
model add this line
cattr_accessor :current_user
恭喜,现在 current_user
在每个模型中都可用,要获取当前用户,只需在任何地方使用以下行
Congrats, now current_user
is available in every model, to get the current user just use the following line everywhere
Team.current_user
注意:添加上述行后重启服务器!
NOTE: Restart the server after adding the lines mentioned above!
现在在你的问题中你可以像使用它
Now in your question you can use it like
def set_default_url
if Team.current_user.id == self.user_id
"/assets/default_black_:style_logo.jpg"
else
"/assets/default_:style_logo.jpg"
end
end
希望这有帮助!
这篇关于如何访问模型中的 current_user 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!