views:

110

answers:

2

My application has the concept of a "Loan". Each loan has a creditor, a debtor, and an amount.

From a database perspective, I know that I want the loans table to look something like this:

|id|Amount|creditor_id|debtor_id|
| 1|   100|          5|        7|

Where creditor/debtor ids reference User ids (i.e., the primary key for rows in my users table).

My question is how I should set this up in ActiveRecord. I can't do something like:

class Loan < ActiveRecord::Base
    has_one :creditor

Since this will cause rails to look for a 'creditors' table (and the creditors are all stored in the users table).

+4  A: 

The option (naturally, well-documented in the Rdoc) is :class_name. I believe the syntax is:

has_one :creditor, :class_name => 'User'

Also, you may want to bookmark this:

http://api.rubyonrails.org/

Could save a few minutes next time.

runako
Fair, but http://api.rubyonrails.org/ has such a terrible UI!
Horace Loeb
True. However, where speed is concerned: Find in a browser window >> Google >> Stack Overflow. :-)
runako
A: 

This is not as easy as it looks. Can users be both creditors and debtors? Can they have more than one loan?

Basically, it looks like you want a self-referential many-to-many relationhip. You want a join model called loan because you have extra data in your join table so you should use has-many :through. Here is a good blog post on the differences between habtm and has-many :through.

There are plenty of examples around of how to do complicated things with your model relationships. Be warned though that all the fancy model setup is not matched by examples of how to then setup your controllers and views. It seems the tutorial writers all steer well clear of full examples of many-to-many relationships with controllers and views because it is pretty hard.

Good luck

srboisvert