# Self referential has\_one

**URL:** <https://www.ruby-forum.com/t/self-referential-has-one/124115>\
**Category:** Rails\
**Created:** [December 24, 2007, 11:03pm UTC](https://www.ruby-forum.com/t/self-referential-has-one/124115 "2007-12-24T23:03:40Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![encmonkey](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/b9e5f3/32.png) [@encmonkey](https://www.ruby-forum.com/u/encmonkey)\
**Post date:** [December 24, 2007, 11:03pm UTC](https://www.ruby-forum.com/t/self-referential-has-one/124115/1 "2007-12-24T23:03:40Z")

</div>

Hello!

I am trying to track ports - think patch panels and servers. There  
are many ports per location, and each port can have zero or one  
connection to another port. I would think that a self referencing  
has\_one relationship would do the trick, but for all the googling and  
such cannot make it quite work.

The ports table would has:  
class CreatePorts \< ActiveRecord::Migration  
def self.up  
create\_table :ports do |t|  
t.column “location\_id”, :integer  
t.column “position”, :integer  
t.column “connection\_id”, :integer  
t.column “name”, :string  
end  
end

The model would has :  
class Port \< ActiveRecord::Base  
belongs\_to :location  
validates\_presence\_of :location\_id

belongs\_to :connection, :class\_name =\> ‘Port’, :foreign\_key =\>  
‘connection\_id’  
end

This model works fine with data in the table, but I can’t create new  
ports - I get an error:  
NoMethodError: You have a nil object when you didn’t expect it!  
The error occurred while evaluating nil.prefetch\_primary\_key?

which I assume is it complaining that there is not a matching ‘nil’  
key in the ports table for the connection\_id to map to.

I didn’t think a join table would work, since it would basically be  
two columns of port ids, which could be entered in either order with  
any given port id unique across both columns.

Is there a better way to do this?

Any advice appreciated!

---

<div class="post-metadata">

**Author:** ![encmonkey](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/b9e5f3/32.png) [@encmonkey](https://www.ruby-forum.com/u/encmonkey)\
**Post date:** [December 26, 2007, 8:08pm UTC](https://www.ruby-forum.com/t/self-referential-has-one/124115/2 "2007-12-26T20:08:11Z")

</div>

Ah - nevermind - I figured it out. I made the n00b mistake of  
calling the association ‘connection’, which of course broke stuff by  
overriding the AR connection method.

oops.
