【问题标题】:Ruby on Rails "undefined method `email' for nil:NilClass"Ruby on Rails“nil:NilClass 的未定义方法‘email’”
【发布时间】:2017-09-21 22:34:25
【问题描述】:

我正在使用“设计”,我想在学生仪表板中调用 current_user.email。但我不断收到相同的“nil:NilClass 的未定义方法 `email'”错误。

学生/index.html.erb

<div class="student-index-header">
    <br><%= current_user.email %></br>
  <div class="student-index-header-text">
    <a class="student-index-header-text-sign-out" href="<%= destroy_user_session_path %>">Sign-out</a>
  </div>
</div>

学生.rb

class Student < ApplicationRecord
  belongs_to :user, optional: true
  validates_presence_of :first_name, :last_name , :age, :description
end

用户.rb

class User < ApplicationRecord
  has_one :tutor
  has_one :student

 # Include default devise modules. Others available are:
 # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
end

【问题讨论】:

  • current_user 未定义。你确定你已经加载了吗?这可能需要登录,但您尚未登录。

标签: ruby-on-rails ruby devise


【解决方案1】:

如果您的用户未登录,Devise 会为 current_user 返回 nil

试试这个:

<%= current_user.email if user_signed_in? %>

如果页面要求用户登录,您还应该将此行添加到您的控制器(这会使上面的 if 子句变得多余,因为我们已经检查了用户是否在控制器中登录):

authenticate_user! unless user_signed_in?

您可能还希望在用户登录后将其重定向回此页面。要了解如何操作,请查看this answer.

【讨论】:

  • Ser Friendzone,非常感谢您帮助我并解决了问题。
  • 很高兴帮助布莱克!
猜你喜欢
  • 2013-03-04
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-16
  • 2012-09-24
相关资源
最近更新 更多