Self-Referential Many-To_many help

Hi,

Despite Josh S.'s great tutorial, I am having trouble getting my
self-referential many-to-many to work properly.

I’d really appreciate it if someone could cast a quick critical eye over
my simple setup. First my join-table migration sets up a source and
destination column for “PaperRelationship”:


t.column :source_paper_id, :integer, :null => false
t.column :destination_paper_id, :integer, :null => false

PaperRelationship Model to go on top of this:

belongs_to :source_paper, :class_name => “Paper”
belongs_to :destination_paper, :class_name => “Paper”

Then in my “Paper” model (the one which I would like to be
self-referential) I have the following 4 has_manys:

has_many :paper_relationships_as_source, :foreign_key =>
“source_paper_id”, :class_name => “PaperRelationship”, :dependent =>
:destroy
has_many :outgoing_papers, :through => :paper_relationships_as_source,
:source => “source_paper”
has_many :paper_relationships_as_destination, :foreign_key =>
“destination_paper_id”, :class_name => “PaperRelationship”, :dependent
=> :destroy
has_many :incoming_papers, :through =>
:paper_relationships_as_destination, :source => “destination_paper”

This all seems to be fine, until I do something like

paper1.outgoing_papers << paper2

I get the MYSQL constraint error:
ActiveRecord::StatementInvalid: Mysql::Error: Column
‘destination_paper_id’ cannot be null: INSERT INTO paper_relationships

Any help is, as always, greatly appreciated.

Thanks for reading,

  • Nex