【问题标题】:How to access current_user object in model?如何访问模型中的 current_user 对象?
【发布时间】:2015-05-02 11:52:01
【问题描述】:

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

用于#的未定义局部变量或方法`current_user'

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 方法适用于其他模型和控制器。我是这样调用这个方法的。

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 。这似乎是一个简单的任务,但我不明白故障在哪里。如果有人在这里帮助我,我将非常感激。

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 devise


【解决方案1】:

current_user 在任何模型中都不可用,要在模型中访问current_user 这样做

在您的应用程序控制器中

before_filter :set_current_user

def set_current_user
  Team.current_user = current_user
end

在您的 Team 模型中添加此行

cattr_accessor :current_user

恭喜,现在current_user 在每个模型中都可用,要获取当前用户,只需在任何地方使用以下行

Team.current_user

注意:添加上述行后重新启动服务器!

现在在您的问题中,您可以像这样使用它

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

希望这会有所帮助!

【讨论】:

  • Team.current_user 即使我已登录也返回 nil
  • 糟糕,很抱歉,我错过了一行,在应用程序控制器中添加此行before_filter :set_current_user,我已经编辑了答案
【解决方案2】:

如果你只使用它一次而不是在调用这个方法时传递 current_user 作为参数,比如

has_attached_file :logo, :styles => { 
  :medium => "200x200#", 
  :thumb => "100x100#", 
  :small => "50x50#" 
}, 
:default_url => :set_default_url(current_user)

在模型中

def set_default_url(current_user)
  if current_user.id == self.user_id
    "/assets/default_black_:style_logo.jpg"
  else
    "/assets/default_:style_logo.jpg"
  end
end

如果您不想要上述步骤,请按照这些步骤操作

转到用户模型

def self.current_user
  Thread.current[:user]
end

def self.current_user=(user)
  Thread.current[:user] = user
end

然后转到应用程序控制器

before_filter :set_current_user

def set_current_user
  User.current_user = current_user
end

现在我们可以轻松地在任何模型中获取 current_user ,而不仅仅是在 Team 中

只需在您的代码中以 User.current_user 的形式给出

def set_default_url
  if User.current_user.id == self.user_id
    "/assets/default_black_:style_logo.jpg"
  else
    "/assets/default_:style_logo.jpg"
  end
end

所以好好利用吧。

希望它能很好地解决您的问题。在任何模型中免费使用

User.current_user 获取当前用户 User.current_user= 分配当前用户。

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多