self referential has_one


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!

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.