Multiple Table Inheiritance (MTI)

I’m trying to create a model hierarchy that looks like this:

class Share

class TwitterShare < Share

class FacebookShare < Share

I’ve used STI in the past, but given the number of potential share types, i don’t think that’s the best option. I’m looking at MTI, where the shares table would hold common share information, and then the subclass tables would have their own distinct fields.

Has anyone used MTI in the past? What I’d really like to do is to have User.find(1).shares return an array holding all shares types. Is that possible?

I think this is what you’re looking for?

class Share < ActiveRecord::Base
  belongs_to :user
  belongs_to :shareable, :polymorphic => true

class TwitterShare < ActiveRecord::Base
  has_one :share, :as => :shareable

class FacebookShare < ActiveRecord::Base
  has_one :share, :as => :shareable

This would let you do the following:


which would return an array of shares that would look like this:

  Share: { :id => 1, :user_id => 1, :shareable_id => 1, :shareable_type => "TwitterShare"},
  Share: { :id => 2, :user_id => 1, :shareable_id => 1, :shareable_type => "FacebookShare"}
1 Like

shoot you’re right. i wasn’t even thinking about this in terms of polymorphic relationships, which i’ve used in the past.


btw - simple polymorphic didn’t really work for my scenario.

this is more what i needed:

so now i can do TwitterShare.create and then get that back when I do User.find(1).shares