Search code examples
ruby-on-railsdevisesingle-table-inheritancesti

Rails Devise STI - undefined local variable or method `users' for <QuizSession>


I'm using single table inheritance so my models Student and Teacher inherit from the same Devise model User (attributes are the same, only the relationships to other models are different).

Now I was trying to display data from an instance of the model QuizSession, which has a one to one relationship with Teacher and a one to many relationship with Student, but I keep getting the error: undefined local variable or method 'users' for #< QuizSession:0xb48e740 > .

Here are my models:

# 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

EDIT: The problem seems to occur when I try to call @quiz_session.students. While the correct QuizSession record is found, apparently it can't resolve .students? I don't understand why, because the User model does have an attribute quiz_session_id which the student model should inherit.


Solution

  • Change this line:

    delegate :teachers, :students, to: :users
    

    To this:

    delegate :teachers, :students, to: :user
    

    The reason for this change is because your model is User, not Users.