开发者

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 mo开发者_如何转开发del
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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜