如何访问模型中的current_user对象? [英] How to access current_user object in model?

查看:66
本文介绍了如何访问模型中的current_user对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的团队模型中编写一个方法,但是current_user显示此错误

I am trying to write a method in my "team" model but current_user is showing this error

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 在任何模型中均不可用,要访问模型中的 current_user ,请执行此操作

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

在您的团队模型中添加此行

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆