# Need help with self-referential has\_many :through associations

**URL:** <https://www.ruby-forum.com/t/need-help-with-self-referential-has-many-through-associations/167085>\
**Category:** Rails\
**Created:** [May 3, 2009, 4:47pm UTC](https://www.ruby-forum.com/t/need-help-with-self-referential-has-many-through-associations/167085 "2009-05-03T16:47:56Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![alexander](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/bc8723/32.png) [@alexander](https://www.ruby-forum.com/u/alexander)\
**Post date:** [May 3, 2009, 4:47pm UTC](https://www.ruby-forum.com/t/need-help-with-self-referential-has-many-through-associations/167085/1 "2009-05-03T16:47:56Z")

</div>

Hi

In my application i need self-referential has\_many :through  
associations, but that i make not work:

Rails -v 2.3.2

The Migrations:

create\_table :pages do |t|  
t.string :name  
t.text :body  
end  
create\_table :links do |t|  
t.integer :from\_page\_id  
t.integer :to\_page\_id  
end

The Models:

class Link \< ActiveRecord::Base

# Associations

belongs\_to :from\_page, :class\_name =\> ‘Page’  
belongs\_to :to\_page, :class\_name =\> ‘Page’  
end

class Page \< ActiveRecord::Base

# Associations

has\_many :links\_sent, :foreign\_key =\> ‘from\_page\_id’, :class\_name =\>  
‘Link’, :dependent =\> :destroy  
has\_many :links\_received, :foreign\_key =\> ‘to\_page\_id’, :class\_name  
=\> ‘Link’, :dependent =\> :destroy  
has\_many :to\_pages, :through =\> :links\_sent  
has\_many :from\_pages, :through =\> :links\_received

# validates

validates\_uniqueness\_of :name  
end

Console:

ruby script/console

> > Page.count  
> > =\> 0
> 
> > from = Page.new(:name =\> “Bla”)  
> > to = Page.new(:name =\> “Bla Bla”)  
> > to.from\_pages  
> > =\> []
> 
> > Link.create(:from\_page =\> from, :to\_page =\> to)  
> > to.from\_pages

=\> [] !!!

What i’m doing wrong?  
I need a page with has many and belongs to many pages.

Thanks
