我有一个student
表和一个classrooms
表。我的学生索引视图中有一行代码
<td><%= student.classroom.classroom_name %></td>
我正在尝试显示与student.classroom_id
关联的教室名称。这段代码在使用sqlite3的本地开发环境中有效,但是当我使用MySQL将代码复制到cPanel Web服务器时,出现此错误
undefined method `classroom_name' for nil:NilClass
有人知道我的代码有什么问题吗?
我已将所有代码从本地安装复制到服务器。
我在迁移中添加了外键。
我已在服务器上运行rails db:migrate
。
classroom.rb
class Classroom < ApplicationRecord
validates :classroom_name, presence: true, length: { minimum: 3, maximum: 50}
has_many :students, dependent: :destroy
has_many :families, through: :students
end
student.rb
class Student < ApplicationRecord
enum status: [ :Active, :Deactive ]
belongs_to :classroom, optional: true
has_many :student_group_assignments
has_many :student_groups, through: :student_group_assignments
end
cPanel服务器undefined method
classroom_name'上针对nil:NilClass的错误
但它确实适用于Rails安装上的本地ruby。
答案 0 :(得分:0)
根据错误,很明显,您正在上课,表中没有该学生的classroom
条目。
但是,在这种情况下,您应该使用
<td><%= student.classroom.try(:classroom_name) %></td>