简体   繁体   中英

Rails has_many through relationship for a user's debtors/creditors

I am writing an app where a user can keep track of which users owe him money (his debtors) and which users he owes money to (his creditors).

This is my debt model:

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

This is my user model:

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

Right now, I am able to get User.debts (Debts where his id = debtor_id) and User.credits (Debts where his id = creditor_id). I want to be able to find the User's debtors (find Debts where his id = creditor_id, and pull up all the debtor_ids of those debts) and the User's creditors (find Debts where his id = debtor_id, and pull up all the creditor_ids of those debts).

In User class you should have two separate relationships

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM