multiple has_one and has_many relationships

42 views Asked by At

so I'm trying to make a relationship between an allocation and a general ledger account, and it's turning out to be a bit more complicated than I initally thought, I was just wondering if there was a more elegant way

So basically an allocation must have a credit and debit account, both of which are general ledger accounts, and I can't use STI because a general ledger account can be a debit account on some allocations but credit account on others.

Now, another feature I want to have is to query all the debits and credits on a particular general ledger account. So a general ledger account now must have many credits and debit transactions. This is what I have so far:

class Allocation
  belongs_to :journal_entry_item
  belongs_to :allocatable, polymorphic: true

  has_one :debit_allocation
  has_one :credit_allocation
  has_one :debit_account, through: :debit_allocation, source: :general_ledger_account
  has_one :credit_account, through: :credit_allocation, source: :general_ledger_account
end

class DebitAllocation
  belongs_to :allocation
  belongs_to :general_ledger_account
end

class CreditAllocation
  belongs_to :allocation
  belongs_to :general_ledger_account
end

class GeneralLedgerAccount
  belongs_to :company

  has_many :debit_allocations
  has_many :credit_allocations
  has_many :debits, through: :debit_allocations, source: :allocation
  has_many :credits, through: :credit_allocations, source: :allocation
end

I feel like there should be a simpler way... Can anyone weigh in? Thanks in advance!

1

There are 1 answers

1
Сергій Назаревич On

What You think about: whether 'Allocation' can be both 'debit' and 'credit'?

If it is not possible, You could define next Models:

 class Allocation
  belongs_to :journal_entry_item
  belongs_to :general_ledger_account

  has_one :general_ledger_account
  has_one :debit_account, source: :general_ledger_account
  has_one :credit_account, source: :general_ledger_account

  def is_debit?
    debit_account&&!credit_account
  end

  def is_credit?
    !debit_account&&credit_account
  end
end

class GeneralLedgerAccount
  belongs_to :company

  has_many :allocations
end