0
votes

In my application, I have the following models:

User

Psychologist has_many classrooms

Teacher has_many classrooms

Parent has_many children

Director belongs_to school

Coordinator belongs_to school

My user model looks like the following:

class User < ActiveRecord
   has_many :roles

   def has_role? role_name
     self.roles.where(role_type: role_name).any?
   end
end

The Role model is polymorphic:

class Role < ApplicationRecord
  belongs_to :user
  belongs_to :roleable, polymorphic: true
end

And the other models are rollable.

My question is the following, it seems that this is not correct, because some models like: Director, Psychologists, Teachers, Coordinator and Parent. They only have relationships and their database tables do not have any other column except created_at, updated_at.

Is it okay to only create these models with relationships and have their tables without data?

1

1 Answers

0
votes

Maybe you intend to use single table inheritance and not polymorphic relationships. If a Psychologist is a User, it should be the case.

Then you need to add a type column of type VARCHAR to the users table, and set up your models like:

class User < ApplicationRecord
  has_many :roles

  def has_role? role_name
    self.roles.where(role_type: role_name).any?
  end
end

class Psychologist < User
  # no need to set up roles
end

class Teacher < User
  # no need to set up roles
end

class Role < ApplicationRecord
  belongs_to :user
  # no polymorphic
end

The type column will be populated with the name of the actual class, like "Teacher" etc.

As an instance of Teacher is also an instance of User, it will have teacher.has_role?('foo') and teacher.roles, and you will be able to create a role like Role.create(user: teacher, name: 'bar').