Reputation: 137
I'm fairly new to Rails
and trying to setup an app that uses several types of users: Teacher
, Student
, Admin
(and likely more to come).
The reason I want different models is because the attributes for the various users differ. For example, Teacher
have topics taught, a profession, and a diploma. Whereas Student
and Admin
do not. Students can leave reviews of teachers, etc.
I thought of having a general User
model for the general information such as name, email, and other contact information and each type of user would inherit of it:
class Admin < User
end
class Teacher < User
end
class Student < User
end
And so on.
I'm using Devise
for authentication and used STI
for differentiating between user roles through a role field in the table.
The thing is, where and how can I tell my app to generate a current_user
of the right class when the user logs in? And where should I store the additional info on each model (ex the profession of a teacher). In the users table?
About the relationship with their objects, for example, a teacher has many topics he teaches. How can I make sure only teachers have topics and not students?
I've looked into CanCan but was utterly confused.
Upvotes: 1
Views: 1074
Reputation: 3700
My advice is : DONT DO THAT ! You are mixing very different concerns and will end up with the infamous God Object.
User is here only for authentication, you should not mix it with your domain models. Teacher / Student / Admin etc should be separate models from User. You can eventually create a People table and have Teacher Student and Admin inherit from it.
class Student < Person
Or have a different table for each of them so there's no possible confusion (also someone might be both a Teacher and an Admin for example, separating stuff keeps your options open)
But whatever you choose keep User out of it !
If you want to tie a User to Teacher / Student / Admin use associations and give each of them a user_id.
class Student < ActiveRecord::Base
belongs_to :user
end
Upvotes: 3
Reputation: 814
Please have a look into this link. Hope this may helpful to you:-
http://funonrails.com/2011/12/multiple-resources-registrations-with/
Also, you can manage relationship with their objects by making model(table) as polymorphic like:-
# Topic Model:
belongs_to :readable, :polymorphic => true
Also in topic model there are two more fields:-
readable_id and readable_type.
# Teacher Model:
has_many :topics, as: :readable
# Sturdent Model:
has_many :topics, as: :readable
Upvotes: 0