Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_one relationship to the same class

I have the following Person class that has a parent that is also another Person. I can't seem to figure out how to get the relations to 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 have added "mom_id" and "dad_id" as integers to my model with a migration. However, when I use the rails console, I'm not able to access mom or dad attributes after settings the mom_id and dad_id. They still return nil.

Any pointers to what I am doing wrong?

like image 369
jasonlfunk Avatar asked Jun 10 '12 04:06

jasonlfunk


1 Answers

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"
like image 82
Nathan Avatar answered Oct 31 '22 15:10

Nathan