D
D
dexdev2015-09-22 19:39:07
Ruby on Rails
dexdev, 2015-09-22 19:39:07

How to link three models correctly?

Good afternoon! There are users and there are companies, companies can have many users, users can have many companies, companies have divisions, now everything is organized like this:

class User < ActiveRecord::Base
  has_many :companies, through: :users_companies
  has_many :users_companies
  has_many :divisions, through: :users_divisions
  has_many :users_divisions
  has_many :users_roles, dependent: :destroy
  has_many :roles, through: :users_roles
end

class Company < ActiveRecord::Base
  has_many :users_companies
  has_many :users, through: :users_companies
  has_many :divisions, dependent: :destroy
end

class Division < ActiveRecord::Base
  has_ancestry
  belongs_to :company
  has_many :users, through: :users_divisions
  has_many :users_divisions
end

in the UsersDivision database added the company_id column, but when the User model is updated, the company_id column becomes NULL, the situation is identical with the Role model, maybe there is some other rails way to link the three models right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Spiridonov, 2015-09-22
@customtema

Introduce another entity, a many-to-many relationship between users and companies.
And yes, I advise you to score on such a thing as "correctness". There are only three important criteria: a) it works, b) it is safe, c) it is fast. The fourth criterion is beautiful (about code design). "Correct" is not on this list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question