Assume that you have people and people have friends. Just as you’ve
described, this is a habtm relationship that refers back to the same
table. Whenever you have a habtm, you need a join table. Here’s a
(partial) migration that describes the two tables:
create_table :people do |t|
t.column “name”, :string
end
create_table :friends_people, :id => false do |t|
t.column “person_id”, :integer
t.column “friend_id”, :integer
end
And now here is the ActiveRecord model:
class Person < ActiveRecord::Base
has_and_belongs_to_many :friends,
:class_name => “Person”,
:join_table => “friends_people”,
:association_foreign_key => “friend_id”,
:foreign_key => “person_id”
end
You’re talking about a self-referential many-many relationship. The
Rails Recipes book has an example of how to do this, plus there are a
few other things in various places. Try googling “ruby rails
self-referential”
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.