How to model relationship for a model to itself

I have a model named User, and the mysql table is users.
Every user can have many friends. of course, every friend is a user.
So, it’s a relationship from user to user.

how to model this?

User has_and_belongs_to_may :users?

then how to define the table ‘users_users’ for this relationship.

it need 2 fields named user_id?

Thanks for your help.

Rockydd wrote:

I have a model named User, and the mysql table is users.
Every user can have many friends. of course, every friend is a user.
So, it’s a relationship from user to user.

how to model this?

User has_and_belongs_to_may :users?

then how to define the table ‘users_users’ for this relationship.

Use the has_and_belongs_to_many :join_table option and name it something
else.

Next, the Friendship concept in a social app might be too important to
hide
its join table. “Friends since 2008”, “BFF”, “sworn enemies”, etc. Maybe
the
joining table should be a Model of its own. Then User gets…

has_many :friends
has_many :users, :through => :friends

…roughly. Can anyone spot what my association is missing?


Phlip

Hi –

On Tue, 22 Apr 2008, Phlip wrote:

has_many :users, :through => :friends
If you’ve got a Friendship model, though, you’d probably want
something like:

has_many :friendships

and then friends through friendships… except you’ll run into the
issue of the symmetry (or lack thereof) of the friendships table,
which of course can’t have two user_id fields. You can deal with this
by having a “friend1_id” and “friend2_id” (or some such thing) field,
and a concept of who has befriended whom. There’s some examples of
this in the comments at:
http://blog.hasmanythrough.com/2006/4/21/self-referential-through

I imagine you could also do something with one friendship row and some
finder SQL, but that will have to await the second cup of coffee :slight_smile:

David


Rails training from David A. Black and Ruby Power and Light:
INTRO TO RAILS June 9-12 Berlin
ADVANCING WITH RAILS June 16-19 Berlin
INTRO TO RAILS June 24-27 London (Skills Matter)
See http://www.rubypal.com for details and updates!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs