views:

65

answers:

1

I have a User and Company model. There are three possible roles that a user can have: Owner, Agent or End-User. Agents and End-Users belong to companies, which in turn belong to Owners. How would you go about making the association between these models?

Would a habtm association be useful here? I.e Users can have and belong to many companies. The only problem is that a user should only belong to a single company. However, owners should be able to own many companies.

Also, I'd need all the users belonging to the company to be removed if the company is destroyed. Or... if the owner is destroyed, all companies (and hence users belonging to those companies) should also be deleted. I'm not sure if a habtm association can do this.

+1  A: 

This is one option which fits your requirements. But it's hard to tell if it is the best approach without understanding the problem domain better.

# script/generate model user company_id:integer role_in_company:string
class User < ActiveRecord::Base
  has_many :owned_companies, :class_name => "Company", :foreign_key => "owner_id", :dependent => :destroy
  belongs_to :company
end

# script/generate model company owner_id:integer
class Company < ActiveRecord::Base
  belongs_to :owner, :class_name => "User"
  has_many :employees, :class_name => "User", :dependent => :destroy
end

The company_id and role_in_company columns are only used for Agents and End Users. Leave them null for owners - that's what the owner_id column is for.

ryanb
Many thanks Ryan! It seems to be working well.
Homar