I'm having a really tricky time modeling this data problem.
My application is basically a messaging app between two types of user object—users and admins. The data for each is the same, but their relationship to messages is slightly different.
A regular user has a single group that all messages are received at. An Admin, however, can send messages to multiple regular users in different groups.
So:
- users have one group, and have many messages through that group
- admins have many groups, and have many users through groups
it is necessary that that the two types of user exist in the same table because the api spec requires that groups are pulled by user id regardless of the type of user.
I keep going around in circles between polymorphism, STI, and self joins, and just cannot for the life of me figure out the right approach.
Any advice is greatly appreciated!
EDIT:
So this is a semi functioning solution. With this, I can get admins from regular user and vice versa, groups, as well as all messages, but only from a reg_user.
From a data perspective, this is still wrong. A regular user will have multiple groups, but the relationships allow you to pull all messages that belong to a user regardless of group. So can be controlled/restricted from the ui/controller.
The spec I have also dictates that a regular user can only have one thread, which this does not adhere to.
UserModel
class User < ApplicationRecord
has_many :groups
has_many :admins, through: :reg_user, source: :user
has_many :messages, through: :groups
has_many :admins, through: :groups
has_many :reg_user, foreign_key: :admin_id, class_name: 'Group'
end