I have stumbled on an interesting challenge regarding active record associations:
I have an Account model which can have multiple and different organisations attached to it (like for example a Company, a Contractor, a Person) and it also has a different role with each association (accountant, owner, viewer, etc.).
So I am not sure whats the best way to associate them.
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…)
EDIT:
here’s the same approach to manage Roles:
EDIT2:
thirth edit, now the relation is: Account has_many Organizations, each Organization has_one Role, an Account has_many Roles through Organizations
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:
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: