Multiple Table Inheiritance (MTI)

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

class Share
end

class TwitterShare < Share
end

class FacebookShare < Share
end

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
end

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

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

This would let you do the following:

User.find(1).shares

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.

thanks!

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

this is more what i needed: GitHub - brunofrank/class-table-inheritance: A plugin to make class table inheritance in Active Record.

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