[英]Rails has_many through relationship for a user's debtors/creditors
我正在编写一个应用程序,用户可以在其中跟踪哪些用户欠他的钱(他的债务人)以及哪个用户欠他的钱(他的债权人)。
这是我的债务模型:
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 =债务人ID)和User.credits(债务,他的ID =债务人ID)。 我希望能够找到用户的债务人(在其id = creditor_id的情况下查找债务,并拉出这些债务的所有债务人ID)和用户的债权人(在其ID =债务人ID的条件下查找债务,并拉出那些债务人的所有creditor_ids债务)。
在用户类中,您应该有两个单独的关系
has_many :debts, :foreign_key => "debtor_id"
has_many :loans, :foreign_key => "creditor_id"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.