Forum: Ruby on Rails table that have many-to-may relationship to itself

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.
Liang G. (Guest)
on 2006-04-20 11:52
In a social netowrk data model, users belongs other users, and can have
many friends as users, so it is a many to many relatioship.

the class definition could be

class User < ApplicationController
   has_mang_ang_belongs_to users


But how it looks like in the mysql database tables in a "joined"  users
table.

The question really is: what is the table looks like when a model has
many and belongs itself.

thx
Brian F. (Guest)
on 2006-04-20 12:09
Hi,

This example is right out of the Rails Recipes book by Chad F.
(http://www.pragmaticprogrammer.com/titles/fr_rr/index.html):

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

brian
Chris T (Guest)
on 2006-04-20 12:17
(Received via mailing list)
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 topic is locked and can not be replied to.