[英]Rails Devise STI - undefined local variable or method `users' for <QuizSession>
我使用的是单表继承,因此我的模型Student和Teacher从同一个Devise模型User继承(属性是相同的,只是与其他模型的关系不同)。
现在,我试图显示来自QuizSession模型实例的数据,该实例与Teacher具有一对一的关系,与Student具有一对多的关系,但是我不断收到错误消息:#的undefined local variable or method 'users' for #< QuizSession:0xb48e740 >
。
这是我的模型:
# app/models/user.rb:
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :quiz_session, optional: true
# Which users subclass the User model
def self.types
%w(Teacher Student)
end
# Add scopes to the parent models for each child model
scope :teachers, -> { where(type: 'Teacher') }
scope :students, -> { where(type: 'Student') }
end
# app/models/teacher.rb:
class Teacher < User
end
# app/models/student.rb:
class Student < User
end
# app/models/quiz_session.rb:
class QuizSession < ApplicationRecord
belongs_to :quiz
has_one :teacher
has_many :students
delegate :teachers, :students, to: :users #<-- this is apparently where the error occurs
end
编辑:当我尝试调用@quiz_session.students
时,似乎会出现问题。 找到正确的QuizSession记录后,显然它无法解析.students? 我不明白为什么,因为用户模型确实具有学生模型应该继承的属性quiz_session_id
。
更改此行:
delegate :teachers, :students, to: :users
对此:
delegate :teachers, :students, to: :user
进行此更改的原因是因为您的模型是用户,而不是用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.