neymar sabin
neymar sabin

Reputation: 13

How do i associate my model in rails between teams, users and organizations?

I am doing a project in rails which allows multiple users to be a part of organization(user belongs to only one organization). Organization has multiple teams and user also can belong to multiple teams. Besides, the organization part I did other associations like this.

class User < ApplicationRecord
   has_and_belongs_to_many :teams
end 

class Team < ApplicationRecord
   has_and_belongs_to_many :users
end

My thought on adding organizations association is like this.

class User < ApplicationRecord
  has_and_belongs_to_many :teams
  belongs_to :organization
end

class Organization < ApplicationRecord
  has_many :users
  has_many :teams
end

class Team < ApplicationRecord
  has_and_belongs_to_many :users
  belongs_to :organization
end

Are there any other ways, so that I can add organization model which would be helpful for future purposes too?

Thank you.

Upvotes: 0

Views: 434

Answers (1)

ActiveModel_Dirty
ActiveModel_Dirty

Reputation: 528

I'd recommend foregoing the has_and_belongs_to_many relationship in favor of has_many through:, which will allow you to have more flexibility with the Organization model.

Something like this:

class User < ApplicationRecord
  has_many :organizations
  has_many :teams, through: :organizations
end

class Team < ApplicationRecord
  has_many :organizations
  has_many :users, through: :organizations
end

class Organization < ApplicationRecord
  belongs_to :users
  belongs_to :teams
end

This way your associations are defined cleanly between three models without the Rails magic of has_and_belongs_to_many. This allows you use of the Organization model.

Upvotes: 1

Related Questions