I'm having trouble with a single table inheritence (STI) data model where a model can be one of the types OR both. I can add a third type, which would be something like TradingCompanyClearingMember
but then I need to duplicate code from both models into the 3rd. Where this becomes especially difficult is defining polymorphic relationships. Is there an easier / better way / alternatives to consider to model this behavior?
class Company < ActiveRecord::Base
validates :type, inclusion: %w(TradingCompany ClearingMember TradingCompanyAndClearingMember)
end
class TradingCompany < Company
has_many :traders, as: :tradeable
belongs_to :clearing_member
end
class ClearingMember < Company
has_many :trading_companies
has_many :contacts
end
class TradingCompanyAndClearingMember < Company
# copied clearing member relationships
has_many :trading_companies
has_many :contacts
# copied trading company relationships
has_many :traders, as: :tradeable
belongs_to :clearing_member
end
class Trader
belongs_to :tradeable, polymorphic: true
end
The closest thing ruby has to multiple inheritance is mixing in modules. You might be able to put the TradingCompany code into a TradingCompanyModule which you import into both trading company type classes. But I think you're probably better served making Company have one TradingCompany and one ClearingMember instead of using inheritance.