使用Rails无法从子索引获取用户电子邮件

时间:2015-02-10 16:15:54

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

我正在尝试在学生索引页面中收到用户电子邮件,但我一直在返回'未定义的方法`email'为零: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>

1 个答案:

答案 0 :(得分:1)

这是因为您students没有user

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