0

我正在尝试使用 facebook graph api 来获取用户的朋友列表。但我的应用只能列出第一个用户的好友列表。例如,当我打开用户 6 的好友列表 6 时,它会显示好友列表 1 的内容。有人知道为什么吗?感谢您的时间和帮助!

用户.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

用户.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>**

朋友.html.erb

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

朋友控制器

class FriendController < ApplicationController

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

1 回答 1

0

你可能只需要改变...

 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

到(对于 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

到(对于 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
于 2014-04-09T22:29:26.467 回答