【发布时间】:2017-05-16 04:04:47
【问题描述】:
我正在使用单表继承,因此我的模型 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,学生模型应该继承它。
【问题讨论】:
-
尝试将
:users更改为:user。 -
谢谢!我将其更改为
delegate :teacher, :student, to: :user,现在它似乎可以工作了! @hashrocket 如果您将其写为答案,我会接受! :)
标签: ruby-on-rails devise single-table-inheritance sti