0

I'm trying to use facebook graph api to get a user's friend list. But my app can only list the first user's friend list. For example, when I open user 6's friend list 6, it will show the friend list 1's content. Does anybody know why? I appreciate your time and help!!

user.rb

 class User < ActiveRecord::Base     
   has_many :friends

        def self.from_omniauth(auth) 
          where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user| 
          user.provider = auth.provider 
          user.uid = auth.uid 
          user.name = auth.info.name 
          user.email = auth.info.email 
          user.oauth_token = auth.credentials.token 
          user.oauth_expires_at = Time.at(auth.credentials.expires_at) 
          user.save! 
          end   
        end 

        def friendslist 
        facebook {|fb| fb.get_connection("me", "friends")}.each do |hash| 
          self.friends.where(:name => hash['name'], :uid => hash['id']).first_or_create 
          end   
        end

         private    def facebook    
       @facebook ||= Koala::Facebook::API.new(oauth_token) 
         end
end

user.html.erb

**<table>
  <tr>
    <th>Name</th>
    <th>Email</th>
    <th>Friends</th>
  </tr>
    <% @user.each do |user| %>
  <tr>
    <td><%= user.name %></td>
      <td><%= user.email %></td>
      <td> <%= link_to "View Friends List", friend_path(user) %></td>
  </tr>
   <% end %>  
</table>**

friend.html.erb

**<table>
  <tr>
    <th>Friends</th>
  </tr>
   <% @friend.each do |friend| %> 
  <tr>
    <td>
        <%= friend.name %>
    </td>
  </tr>
   <% end %>  
</table>**

friend controller

class FriendController < ApplicationController

    def index
    @friend = Friend.all
      respond_to do |format|
     format.html
     format.json { render json: @friend }
    end
  end
end

1 Answers1

0

You may simply need to change...

 def friendslist 
    facebook {|fb| fb.get_connection("me", "friends")}.each do |hash| 
      self.friends.where(:name => hash['name'], :uid => hash['id']).first_or_create 
      end   
  end

to (for Rails <=3)

 def friendslist 
    facebook {|fb| fb.get_connection("me", "friends")}.each do |hash| 
      self.friends.find_or_create_by_name_and_uid(hash['name'],hash['id'])
      end   
  end

to (for Rails 4)

 def friendslist 
    facebook {|fb| fb.get_connection("me", "friends")}.each do |hash| 
      self.friends.find_or_create_by(:name => hash['name'], :uid => hash['id'])
      end   
  end
blotto
  • 3,387
  • 1
  • 19
  • 19