I'm taking Elimantas' example, corrected some logic errors. basically, you have an Account with N Organizations (which is a polymorphic model and has relation with one of Company, Contractor, etc...)
class Account < ActiveRecord::Base
has_many :organizations
end
class Organization < ActiveRecord::Base
belongs_to :account
belongs_to :resource, :polymorphic => true
end
class Company < ActiveRecord::Base
has_many :organizations, :as => :resource
end
class Contractor < ActiveRecord::Base
has_many :organizations, :as => :resource
end
[...etc...]
EDIT:
here's the same approach to manage Roles:
# just edited Account model with role.
class Account < ActiveRecord::Base
has_many :organizations
has_one :role
end
class Role < ActiveRecord::Base
belongs_to :account
belongs_to :resource, :polymorphic => true
end
class Accountant < ActiveRecord::Base
has_one :role, :as => :resource
end
class Owner < ActiveRecord::Base
has_one :role, :as => :resource
end
EDIT2:
thirth edit, now the relation is: Account has_many Organizations, each Organization has_one Role, an Account has_many Roles through Organizations
class Account < ActiveRecord::Base
has_many :organizations
has_many :roles, :through => :organizations
end
class Role < ActiveRecord::Base
belongs_to :resource, :polymorphic => true
end
class Accountant < ActiveRecord::Base
has_one :role, :as => :resource
end
class Owner < ActiveRecord::Base
has_one :role, :as => :resource
end
is this right?
EDIT3: Role as non AR model:
It may depend by how many Roles you plan to have, or you may have a name:string field where specify 'Accountant', 'Owner', and so on.
if you don't plan to put Role as AR model, then you can define an integer column called 'role_id' and use a costant with an hash in the organization model:
class Organization < ActiveRecord::Base
belongs_to :account
ROLES={'Accountant' => 1, 'Owner' => 2 }
# get role as literal name
def role
ROLES.invert[role_id]
end
end
this way you'll have an Account with many Organizations, each of them with a specific Role regarding that specific Account.
EDIT4: code example of EDIT3
the following code is a raw example of how it might look this association:
# new account
a = Account.new(....)
# new company & organization with a role
comp = Company.create(....)
org1 = Organization.new(:role_id => 1, ....)
org1.resource = comp
# new Contractor & Organization with another role
contr = Contractor.create(....)
org2 = Organization.new(:role_id => 2, ....)
org2.resource = contr
a.organizations << org1
a.organizations << org2
# save Account, it will have 2 different organizations, each one with a specific role
a.save