Justin
Justin

Reputation: 1956

Rails "Sometimes Has One" Relationships

This is probably a newbie question, but I can't seem to think of a good solution. I have a company table that has_many users through groups that can also be administrators of the company (enabling them to edit the company but only one company per user).

What's the best way to set this up in Rails?

I can't add an admin field to the user table, because it wouldn't discriminate which company he/she is administrating. But if I do a company_id field, what would that relationship look like in Rails (since it's a sort of somtimes_has_one relationship!). I could leave it without a relationship, but that doesn't seem proper...

Thanks in advance for any help!

Upvotes: 1

Views: 437

Answers (1)

Andrei S
Andrei S

Reputation: 6516

From what I understand, you have a user which might belong to a company, and if it does, it might actually administer it.

You could setup Group to have for example, company_id, user_id and an admin field (this way you get to know which users belong to which company, and if they also administrate that company)

For a user to belong to just one company you could add a validation for uniqueness per two columns (company_id and user_id)

You could get one company's administrators by doing

class Company < ActiveRecord::Base
  has_many :groups
  has_many :users, through: :groups
  has_many :administrators, through: :groups, source: :user, conditions: ["groups.admin = ?", true]
end

and call company.administrators or company.users for all users

You could also do something like

class User < ActiveRecord::Base
  has_one :group
  has_one :company, through: :group
  has_one :administered_company, through: :group, source: :company, conditions: ["groups.admin = ?", true]
end

so you can call user.company or user.administered_company

and so on...

Upvotes: 1

Related Questions