Class that belongs_to another Class twice?

I have Class Referral which takes both a giver and receiver as a Person.
As is, @person.referrals returns all referrals as appropriate. Using
built in AR methods, @referral.person returns the receiver of the
referral. To find out who issued the referral, I have created an
instance method "giver" so that @referral.giver returns the Person who
gave it. I looked at Chad Fowler's "Self-Referential MtM Models" but
I'm not sure my situation is the same. The current setup I have works,
but I'm not sure if there is a better Rails way to do this.

>MIGRATIONclass CreateReferrals < ActiveRecord::Migration
  def self.up
    create_table :referrals do |t|
      t.column :giver_id, :integer, :null => false
      t.column :receiver_id, :integer, :null => false
      t.column :body, :text, :null => false
      t.column :created_at, :datetime

>REFERRAL MODELclass Referral < ActiveRecord::Base
  belongs_to :person

     has_one :giver, :class_name => "Person"

  validates_uniqueness_of :giver_id, :scope => :receiver_id

  def giver

>PERSON MODELclass Person < ActiveRecord::Base

  has_many :referrals, :foreign_key => "receiver_id"

Posted via

I think you should be able to just add the has_one association to the
referral model and get your attribute accessor for free...



Ok. Here's what I've got...

## Migrations

    create_table "people" do |t|
      t.column "name", :string
    create_table "referrals" do |t|
      t.column "giver_id", :integer
      t.column "receiver_id", :integer

## Models

class Person < ActiveRecord::Base
  has_many :referrals, :foreign_key => "receiver_id"

class Referral < ActiveRecord::Base
  belongs_to :receiver, :class_name => "Person", :foreign_key =>
  belongs_to :giver, :class_name => "Person", :foreign_key =>

## Console

r = Person.create
g = Person.create
ref = Referral.create(:giver => g, :receiver => r)


r.referrals #=> [ ref ]
g.referrals #=> []
ref.giver #=> g
ref.receiver #=> r