我使用單表繼承,所以我的模型Student和Teacher從相同的Devise模型User繼承(屬性相同,只有與其他模型的關係是不同)。Rails設計STI - 未定義的局部變量或方法`users'<QuizSession>
現在我試圖顯示模型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'''。 – hashrocket
謝謝!我將它改爲'委託:老師,:學生,到::用戶',現在它似乎工作! @hashrocket如果你寫它作爲答案我會接受它! :) – megahra