0

I am using devise and Pundit in my application. I have many users like Student, Teacher, Admin, Editor. I added a enum role in my User devise model. Now the part i am not understanding is - student will have its own attributes, likewise teachers will have its own attribute. For example student will have school name whereas teacher will have a class. Now if i put everything in user model i will have many null values. How can i use this roles to create a model for each i.e Student, Teacher, Sponsor so i can add those extra attributes own the respective student, teacher , sponsor models. Any help will be appreciated

enum role: [:teacher, :student, :sponsor, :admin]

Expected result: To have a model that has attributes for related to the model itself. Eg. Student will have a column name School in its model instead of User model.

Zaa
  • 23
  • 8
  • Did you thougt about Single Table Inheritance? https://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html – Archer Jun 25 '19 at 07:09
  • I looked into it and found out that the enum role will be more suitable in my approach as i am going to use Pundit . Also,one user cannot have multiple roles. I won't be using polymorphic or STI. – Zaa Jun 25 '19 at 07:12
  • 1
    You could have a basic `User` model which handles authentication, and associate it with an appropriate `StudentProfile`, `TeacherProfile` etc model with the required attributes for the given user type – Jon Jun 25 '19 at 07:58
  • Multi-table inheritance is not something Rails is good at. I've had a similar problem and have used gems like [active_record-acts_as](https://github.com/hzamani/active_record-acts_as). It may just be better to accept some duplicate code and make separate models if they are different enough that STI or enums don't make sense. It just gets overly complicated otherwise. – Mark Merritt Jun 25 '19 at 08:07
  • As @Jon has mentioned, you need to use user model for authentication and authorization and store each profile in different model with required validation. You need to use polymorphic for this. – dharmesh Jun 25 '19 at 08:07
  • @Jon Could you elaborate on this? As Dharmesh mentioned should i use polymorphic? Can't i use the interger value of enums to tell that the rest of the data after authentication goes to 'this' model? – Zaa Jun 25 '19 at 08:35
  • I have suggestion to use postgres and add a `attribute` column to user model with `hstore` type.so u can have its own attribute field for each role – Abhishek Aravindan Jun 25 '19 at 10:26

1 Answers1

0

Thanks for the post! I am also looking for the guide.

class User < ApplicationRecord 
has_one :profile
has_many :classrooms

enum role: [:teacher, :student, :sponsor, :admin]
end

a. Does it mean that all roles have attributes from the associations?

b. For STI...does it mean all the associations in the subclass will leave the null?

class Teacher < User
  has_many :classrooms
end

Thank you!