Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - two foreign keys on one model both refer to same model

I'm fairly new to ActiveRecord associations. I'm sketching out an application that tracks who owes each other money among a set of users. An Expense model and a User model seem like natural choices, I'm just not sure how to define the relationship between the two. For example, I want to track the creditor ("owner") and the debtor of each expense, but that's really just two foreign keys that go back to User. In addition, each user can have multiple expenses (both as creditor and debtor) My best guess for the associations thus far is something like:

class Expense
    # belongs_to or has_one here?
    # Not sure about class => User syntax:
    # need to alias to foreign keys that reference the same model
    belongs_to :creditor, :class => User 
    belongs_to :debtor, :class => User

class User
    # has_many expenses defines a creditor relationship (user owns expense)
    # how to define debtor relationship? (belongs_to...?)
    has_and_belongs_to_many :expenses

I've read the Rails guide on associations but I'm still fairly lost on foreign keys and join tables. Any input is much appreciated!

like image 724
ark Avatar asked Feb 07 '12 08:02

ark


People also ask

Can two foreign keys reference each other?

Yes, it is okay to have two fk to the same pk in one table. Yes - of course!

What is foreign key in Ruby on Rails?

A foreign key is a field in one database that uniquely identifies a row in another table. For this example, our foreign key in the expenses table will identify which category each expense should fall under.


1 Answers

So this is definately not a has_and_belongs_to_many thats for many-to-many relationships. You just need to use a couple has_many relationships. I think it should end up looking like this:

Edit: oops I fudged that a bit that up sorry let me have another go:

class Expense
  # make sure expense table has 'creditor_id' and 'debtor_id' rows
  belongs_to :creditor, :class_name => "User", :foreign_key => :creditor_id
  belongs_to :debtor, :class_name => "User", :foreign_key => :debtor_id

class User
  has_many :debts, :class_name => "Expense", :foreign_key => :debtor_id
  has_many :credits, :class_name => "Expense", :foreign_key => :creditor_id
like image 184
Matthew Avatar answered Sep 27 '22 21:09

Matthew