Search code examples
ruby-on-rails-3has-manysingle-table-inheritancebelongs-to

Dynamically typed associations with STI models


I have a parent model Account with multiple subclasses using STI. I want to associate another model Transaction using a belongs_to relationship to Account. The referenced account could be either an Asset or a Liability.

class Account < ActiveRecord::Base end
class Asset < Account end
class Liability < Account end

My transaction model belongs_to Account

class Transaction < ActiveRecord::Base
  belongs_to :account #Either an Asset or Liability model
end

I want to be able to set a transaction's account to either an Asset or a Liability. However, I get a TypeMismatch error when I set the transaction's account to an Asset or Liablity since it isn't the parent class Account.

Note: I think this could be solved using polymorphism on the belongs_to association, but it seems unnecessary to specify the class in a type column when the referenced models all use the same underlying table.


Solution

  • It turns out that this code works as is. You don't need to specify a polymorphic type on the associated model to the STI model.

    The type mismatch error I was receiving was because my STI base class was actually "Account::Base" and I simply had "Account" as the class name.