# Self-Referential Many-To\_many help

**URL:** <https://www.ruby-forum.com/t/self-referential-many-to-many-help/135959>\
**Category:** Rails\
**Created:** [April 27, 2008, 12:52am UTC](https://www.ruby-forum.com/t/self-referential-many-to-many-help/135959 "2008-04-27T00:52:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jazcyk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e56c9b/32.png) [@jazcyk](https://www.ruby-forum.com/u/jazcyk)\
**Post date:** [April 27, 2008, 12:52am UTC](https://www.ruby-forum.com/t/self-referential-many-to-many-help/135959/1 "2008-04-27T00:52:42Z")

</div>

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
