简体   繁体   中英

Devise and multiple users models

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM