无法从具有 Rails 的子索引获取用户电子邮件

Can't get user email from child index with Rails

我试图在学生索引页面中获取用户电子邮件,但我一直返回 'undefined method `email' nil:NilClass'

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable 

  has_many :posts
  has_many :students
  belongs_to :role

end

class Student < ActiveRecord::Base
  belongs_to :user
  belongs_to :franchise
  belongs_to :preschool
end

在我的学生索引页中我有

<% @students.each do |student| %>
    <tr>
        <td><%= student.user.email %></td>

发生这种情况是因为您有 students 而没有 user

<td><%= student.user.try(:email) || 'Without User' %></td>