Forum: Ruby on Rails need help with self-referential has_many :through associations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
alexander (Guest)
on 2009-05-03 18:47
(Received via mailing list)
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
This topic is locked and can not be replied to.