Rails通过与用户的债务人/债权人的关系来管理

时间:2013-06-30 17:46:50

标签: ruby-on-rails ruby models has-many-through

我正在编写一个应用程序,用户可以跟踪哪些用户欠他的钱(他的债务人)以及他欠钱的用户(他的债权人)。

这是我的债务模式:

class Debt < ActiveRecord::Base
  attr_accessible :amount, :bill_id, :creditor_id, :debtor_id, :is_a_payment

  belongs_to :bill
  belongs_to :debtor,
    :class_name => "User",
    :foreign_key => :debtor_id

  belongs_to :creditor,
    :class_name => "User",
    :foreign_key => :creditor_id
end

这是我的用户模型:

class User < ActiveRecord::Base
  attr_accessible :password, :username, :email

  has_many :debts,
    :foreign_key => "debtor_id"

  has_many :debtors,
    :through => :debts,
    :source => :user

  has_many :credits, 
    :class_name => "Debt",
    :foreign_key => "creditor_id"
end

现在,我可以获得User.debts(债务,其id = debtor_id)和User.credits(债务,其ID = creditor_id)。我希望能够找到用户的债务人(找到他的id = creditor_id的债务,并提取债务的所有debtor_ids)和用户的债权人(查找他的id = debtor_id的债务,并提取所有债权人的债权人债务)。

1 个答案:

答案 0 :(得分:0)

在User类中,您应该有两个单独的关系

has_many :debts, :foreign_key => "debtor_id"
has_many :loans, :foreign_key => "creditor_id"