Forum: Ruby on Rails Some advice on DB modeling

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Ramin B. (Guest)
on 2005-11-21 21:58
(Received via mailing list)
I need some help designing my database. i am trying to create a
site very similar to MySpace, Freindster, etc. I want each of my users
to be
able to add other users as friends. I'm just not sure how to set up my

I have a User object. I'm guessing I need some other table/model to
the associations between the users. I created an Association model and
that User has_many :associations and that Association belongs_to User.
that doesn't seem right.

Any help would be greatly appreciated.
Lee I. (Guest)
on 2005-11-21 22:22
(Received via mailing list)
Ramin wrote:

> Any help would be greatly appreciated.
Try this.

CREATE TABLE `friends` (
  `user_id` int(11) NOT NULL default '0',
  `friend_id` int(11) NOT NULL default '0',
  KEY `user_id` (`user_id`),
  KEY `friend_id` (`friend_id`),
  CONSTRAINT `friends_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users`
  CONSTRAINT `friends_ibfk_2` FOREIGN KEY (`friend_id`) REFERENCES
`users` (`id`)


class User < ActiveRecord::Base
  has_many :friends, :join_table => 'friends', :class_name => 'User',
:foreign_key => 'friend_id'

  def add_friend(friend)
    friends << friend
Ramin B. (Guest)
on 2005-11-21 23:23
(Received via mailing list)
Hi, thanks for your suggestions.. however, I'm getting the following

Unknown key(s): join_table

I can't find the join_table option in the has_many documentation.
Lee I. (Guest)
on 2005-11-21 23:39
(Received via mailing list)
Sorry about that.  It should be:

has_and_belongs_to_many :friends, :join_table => 'friends', :class_name
=> 'User', :foreign_key => 'friend_id'

You can also access the inverse association with:

has_and_belongs_to_many :friends_of, :join_table => 'friends',
:class_name => 'User', :foreign_key => 'user_id',
:association_foreign_key => 'friend_id'
This topic is locked and can not be replied to.