I've created a User
model with Devise and added a type
column etc., so the models Student
and Teacher
could inherit from it. All of this worked great. My Teacher
model has a one to many relationship to the model Course
, where all the data about a teachers courses is stored.
My problem: the Devise helper current_user.courses
doesn't work because the courses
table has no column user_id
. How can I make current_user
be able to resolve .courses
, even though the attribute in courses is called teacher_id
?
I'm a Rails newbie, so any help would be appreciated! :)
EDIT: refined question and added schema and models.
# schema.rb:
create_table "courses", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "teacher_id"
t.index ["teacher_id"], name: "index_courses_on_teacher_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.string "type"
t.integer "quiz_session_id"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["quiz_session_id"], name: "index_users_on_quiz_session_id"
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
# /app/models/course.rb:
class Course < ApplicationRecord
belongs_to :teacher
has_many :students
delegate :teachers, :students, to: :users
end
# /app/models/user.rb:
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :courses
# 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