0
votes

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.

1
Did you thougt about Single Table Inheritance? api.rubyonrails.org/classes/ActiveRecord/Inheritance.htmlArcher
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
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 typeJon
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. 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
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

1 Answers

0
votes

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!