0
votes

I have a STI called Person, I have 3 types: Contact, User and Tenant. Contact and Tenant belongs to one organization, so they have an organization_id column right in the "people" table.

The issue is that the type User may have multiple organizations, so it has a dedicated table named "users_privileges". Currently, the organization_id in the table "people" is null for the type User, since many users have two organizations.

Is there anyway to tell ActiveRecord when I do let say Person.all, that for the type User, it must not check the column organization_id in the table "people" and look for the has_many in "users_privileges" table?

1
Is this a polymorphic association (eg belongs_to :person, polymorphic: true) or Single Table Inheritance?hmind
You are right, it's STI. I was doing polymorphic stuff while writing it, edited!allaire

1 Answers

0
votes

You can achieve this by setting the correct relation in each of the subclasses, so you would put a belongs_to in Contact and Tenant, while putting one of the has_many variants in User.

The result would of course be that if you say Person.all, some of the resulting objects would have respond to #organizations, and some #organization. You can work around this by adding a method #organizations to Contact and Tenant, and have it just return the one organzation in an array.