Puches
Puches

Reputation: 70

Ruby on Rails Relationship

I am currently building a registration system which will need to create both a user and an organization. The Organization needs to have an Owner or System Admin. I believe my second option is best as I can create the Organization, a Sys Admin Role and a User without any circular database issues. My fear with the First option is that an Organization is owned by a user and that user also belongs to that organization.

First --

Class User
  belongs_to :organization
  belongs_to :role
  has_one :organization_as_owner, class_name: "Organization", foreign_key: "owner_id"

Class Organization
  belongs_to :owner, class_name: "User"
  has_many :users
  has_many :roles

Class Role
  belongs_to :organization
  has_many :users

Second --

Class User
  belongs_to :organization
  belongs_to :role

Class Organization
  has_many :users
  has_many :roles

Class Role
  belongs_to: organization
  has_many :users

Using the Second option, I would utilize a permissions table for the Sys Admin, and permit them to add new Roles, etc.. Which setup would you prefer and why? Would using a has_many through on either Option be beneficial?

Upvotes: 0

Views: 70

Answers (1)

derekyau
derekyau

Reputation: 2946

I would probably set up the relationships like this:

Class User
  belongs_to :organization
  belongs_to :role

Class Organization
  has_many :users
  has_many :roles

Class Role
  has_many :users
  belongs_to: organization

This is assuming all users have only one role. This way, you can make the following calls:

user.role user.organization

organization.users organization.roles (this will just collectively list all the roles that the users inside the org have, can always run a uniq! on this if necessary

role.user role.organization

However, I think you should also probably take a look at the excellent rolify gem that could probably help you do this out of the box: https://github.com/EppO/rolify

Upvotes: 1

Related Questions