【问题标题】:multiple has_one and has_many relationships多个 has_one 和 has_many 关系
【发布时间】:2015-06-25 02:59:41
【问题描述】:

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

所以基本上分配必须有一个贷方和借方账户,这两个账户都是总账账户,我不能使用 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

我觉得应该有一个更简单的方法......有人可以权衡吗?提前致谢!

【问题讨论】:

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


    【解决方案1】:

    您的想法是:“分配”是否可以既是“借方”又可以是“贷方”?

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

     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
    

    【讨论】:

    • 分配必须是借记贷记。在会计中,必须有一个交易来自的账户,以及交易进入的账户
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    相关资源
    最近更新 更多