Has_one relation to one class

I have the following class Person, which has a parent, which is also another Person. I can't figure out how to make relationships work.

class Person < ActiveRecord::Base
  attr_accessible :mom, :dad

  has_one :mom, :class_name => 'Person', :primary_key => "mom_id", :foreign_key => "id"
  has_one :dad, :class_name => 'Person', :primary_key => "dad_id", :foreign_key => "id"    
end

I added mom_id and dad_id as integers to my migration model. However, when I use rails console, I can’t access the attributes momeither dadafter the settings mom_idand dad_id. They come back anyway nil.

Any guidance on what I'm doing wrong?

+5
source share
1 answer

I agree with @Andrew, this should be belongs_to

belongs_to :mom, :class_name => "Person", :foreign_key => "mom_id"
belongs_to :dad, :class_name => "Person", :foreign_key => "dad_id"
+8
source

All Articles