【问题标题】:undefined local variable or method `current_user'未定义的局部变量或方法“current_user”
【发布时间】:2013-12-17 00:57:18
【问题描述】:

我正在按照teamtreehouse.com guide 构建我的第一个Ruby on Rails 应用程序(ruby 2.0.0p353)。

我正在使用 devise 3.2.2 devise 并且在 application.html.erb 中我想使用 devise 的“current_user”来显示登录用户的名称。

这里是我使用“current_user”的代码:

    <ul class="nav navbar-nav pull-right">
      <li><%= link_to current_user.first_name, "#" %></li> 
      <li><%= link_to "Log Out", destroy_user_session_path, method: :delete %></li> 
    </ul>

routes.db:

Treebook::Application.routes.draw do
   devise_for :t_busers
   resources :statuses
   root to: 'statuses#index'
end

但是在运行我的应用程序时,我总是收到以下错误:

undefined local variable or method `current_user' for #<#<Class:0x007f98b1d0edb8>:0x007f98b1cff6d8>

我在使用其他设计方法时遇到了同样的错误。无论我是否已登录,我都会收到错误消息。设计的注册、编辑等似乎工作正常。我试过把“before_filter:authenticate_user!”按照设计文档中的说明进入 application_controller.rb ,但这也不起作用。

为了在视图中使用 devise 的助手,我需要做些什么吗?

【问题讨论】:

  • 您在使用 current_user 方法之前是否已登录?你是如何使用它的?能具体一点吗
  • 如果您需要帮助,您应该包含问题所在的代码示例。
  • 谢谢,我已根据您的反馈更新了帖子。
  • 你的路线中有devise_for :users吗?
  • @juanpastas:你的意思是我可以用“rake routes”看到的路线吗?里面没有devise_for :users

标签: ruby-on-rails devise


【解决方案1】:

从你的路由文件中,助手应该是

current_t_buser

来自devise的文档

请注意,如果您的设计模型不是“用户”而是“成员”, 那么你应该使用的助手是:

before_filter :authenticate_member!

member_signed_in?

当前成员

成员会话

【讨论】:

  • 这解决了!谢谢!我是 Rails 新手,当我将模型命名为“TBuser”而不是“user”时,我想我没有得到“约定优于配置”这句话!
【解决方案2】:

更改您的路线文件:

devise_for :t_busers

到:

devise_for :users

那么你应该可以使用current_user。这假设您有一个名为 User 的模型及其对应表 users

【讨论】:

  • 我将模型命名为TBuser :-( 问题已解决。我需要将模型名称更改为user 或使用current_t_buser。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 2017-01-26
相关资源
最近更新 更多