A User to User Relationship

You'll need a many-many relationship with User to itself. You use two
tables for this kind of relationship:

- users
- user_user

user_user has no id column, but does have user_one_id and user_two_id
columns. It's basically a map of friends:

user id=1 is friends with user id=2
user id=1 is friends with user id=3
user id=2 is friends with user id=4


Just as you wuold use 'belongs to' and 'has many' in your model, you

   has_and_belongs_to_many :users, :join_table => "user_user"

Rails should then give you nice friendly access to your friends. You
don't even need to define a single reference in the user table! I
haven't used it myself yet, but I believe you'll get access to the
friends as an array :-

my_user = User.find(:first)

(I may be wrong!)


I have done a similar thing, and I created a friendship model for this.

The main reason is that in my system a friendship goes through multiple
stages. One user initiates a friendship request or invite, and the
other user either accepts (establishes a friendship) or rejects the
offer. Then at any time, one user might terminate the friendship. I
feel there is enough information here to warrant another model, and a
few columns in the friendship table.

I always query this model from the perspective of the active user (I
provide the user_id as a query condition), which avoids having to deal
with queries that include the user table twice. Then again, I'm kind of
a newbie, and maybe avoiding the problem is not your preference. :slight_smile:

I don't have my code on me, but I hope this is a little helpful.