与 STI 模型的动态类型关联
我有一个使用 STI 的父模型 Account 和多个子类。我想使用“belongs_to”关系将另一个模型“Transaction”关联到“Account”。引用的帐户可以是资产或负债。
class Account < ActiveRecord::Base end
class Asset < Account end
class Liability < Account end
我的交易模型属于帐户
class Transaction < ActiveRecord::Base
belongs_to :account #Either an Asset or Liability model
end
我希望能够将交易的帐户设置为资产或负债。但是,当我将交易的帐户设置为资产或负债时,我收到 TypeMismatch 错误,因为它不是父类Account。
注意:我认为这可以使用belongs_to关联上的多态性来解决,但是当引用的模型都使用相同的基础表时,似乎没有必要在类型列中指定类。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明,这段代码可以按原样工作。您不需要在 STI 模型的关联模型上指定多态类型。
我收到的类型不匹配错误是因为我的 STI 基类实际上是“Account::Base”,而我只是将“Account”作为类名。
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.