多个has_one和has_many关系

时间:2015-06-25 02:59:42

标签: ruby-on-rails ruby-on-rails-4 activerecord associations has-many

所以我试图在分配帐户和总帐帐户之间建立关系,而且它比我最初想的要复杂一点,我只是想知道是否有更优雅的方式

所以基本上一个分配必须有一个信用卡和借记卡帐户,这两个帐户都是总帐帐户,我不能使用STI,因为总帐帐户可以是某些分配的借方帐户,但其他人可以使用信用帐户

现在,我想要的另一个功能是查询特定总帐帐户上的所有借记和贷记。因此,总帐帐户现在必须有许多贷记和借记交易。这就是我到目前为止所做的:

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

我觉得应该有一个更简单的方法......任何人都可以称重吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

您的想法:是否'分配'既可以'借记'和'信用'?

如果不可能,您可以定义下一个模型:

 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