SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2004
    Location
    NC
    Posts
    194
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Problems w/ User having many friends

    This seems so easy but I keep hitting a brick wall on this.

    I have this modeling:

    Code:
     class User < ActiveRecord::Base
       has_many :friendships
       has_many :friends, :through => :friendships #...
     end
      
     class Friendship < ActiveRecord::Base
       belongs_to :user
       belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id'
    end
    I have these 2 records in the friends table

    user_id, friend_id
    3 4
    3 5

    Now when I try to select all friends that belong to User of id 3, using this select I get one record instead of 2:

    @users = User.find:all, :include=>[:friendships], :conditions=>["friendships.user_id=?",3])

    Any ideas how I can model this and query this correctly to get both records belonging to User 3?

    Thanks a whole lot!

    Clem

  2. #2
    SitePoint Evangelist
    Join Date
    Feb 2006
    Location
    Worcs. UK
    Posts
    404
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Have you looked at has_and_belongs_to_many ? I think that would achieve what you are after. You'd drop the friendships table, Friendship class and add a join table called "fiends_users" with two fields: friend_id and user_id.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •