Search code examples
ruby-on-railsmodelassociationssocial-networking

Find friends and create a users array


I have a basic social network. I'm trying to create a friends method that returns an array of users. Some user :ids are in the :user_id attribute and some are in the :friend_id attribute. I don't want to return the current_user.id. I only want to return the :name, :id and :uid attributes. I don't know where to go from here.

I hope I simplified enough, please tell me if my question is lacking information.

Thank you!

class User < ActiveRecord::Base
  has_many :friendships, :conditions => {:accepted => true}
  has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id", :conditions => {:accepted => true}

  attr_accessible :name, :oauth_expires_at, :oauth_token, :provider, :uid

  def friends
    friendships.preload(:friend) + inverse_friendships.preload(:user)
  end
end

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"
  attr_accessible :accepted, :friend_id, :user_id, :friend
end

Solution

  • How about this:

    class User
      ...
      def friends
        friendships.map { |f| [f.name, f.id, f.uid] }
      end
    
    end