has_one self reference

Imagine the following situation:

model Person, with the default name, address, location data. Person has either one or no superior which in turn is also a Person model instance.

I would expect something like has_one :superior, :class_name => "Person"

but where would I place the belongs_to line that goes with it and what arguments do I need to supply? And what kind of foreign keys do I need to specify in my migration?

I would like for the following to work:

bossman = Person.new :name => "Mr. Bossman" person1 = Person.new :name => "John" person2 = Person.new :name => "Jane"

person1.superior = bossman person2.superior = bossman

person1.superior.name # => "Mr. Bossman"

I wonder what kind of columns I need for this in my Persons table manually specified and which columns are virtual. I experimented a bit already and got something quite similar, but for some reason I was able to modify the person1.superior_id independantly of the person1.superior object. I'd rather have nothing to do with the _id and shield it from being used directly.

I think you just need it to be belongs_to :superior and then it all just works. The foreign key has to sit somewhere and it can't be on the superior (or else he'd only be able to be the superior of one person).

Fred

Frederick Cheung wrote: