Dynamically typed associations with STI models

I have a parent model Account with multiple subclasses using STI. I want to bind another transaction of the model using the relation own_to to Account. The specified account may 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 up a transaction account for either Assets or Responsibility. However, I get a TypeMismatch error when I set up a transactional account for Asset or Liablity, since it is not a parent class account.

Note. I think that this could be solved using polymorphism in the belongs_to association, but there is no need to specify the class in the type column when the reference models use the same base table.

+3
source share
1 answer

Turns out this code works as it is. You do not need to specify the polymorphic type of the associated model with the STI model.

The type mismatch error I was getting was that my STI base class was actually “Account :: Base” and I just had an “account” as the class name.

+2
source

Source: https://habr.com/ru/post/1787239/


All Articles