I'm trying to allow users that have connected their Facebook accounts to my rails app to find their Facebook friends that have already registered in the app, preferably in an index like format (similar to Formspring's display).
Currently I'm using Devise, OAuth+Fbook Javascript SDK, and Koala. I have the Facebook UID of each user that connects their Facebook saved in the db, but I don't know how to filter through the results of the Facebook API call @friends = @graph.get_connections("me", "friends") in order to display the users that have matching UID's to the API call data.
Any thoughts? There's probably an even better way, so lemme know if any additional info is needed. Thanks very much for your help!
EDIT (screenshot of index action in users controller)
Note in @oauth, app id and app secret are cropped out in the example image
If you can get an array of UID's for the user's friends, you can find them all in a single SQL statement using IN
(some handwaving and/or pseudocode here, depending on attributes, etc):
uids = @friends.collect(&:uid)
# uids is an array of Facebook UID's, say [1234, 5678, 9012]
registered_friends = User.where('fb_uid IN (?)', uids)
# "SELECT users.* FROM users WHERE (fb_uid IN (1234, 5678, 9012))"
If your Facebook data is in another model, you can select off that model and do an includes
to bring in the user.
registered_friends = Authorizations.where(:type => 'Facebook') \
.where('fb_uid IN (?)', uids).includes(:user).collect(&:user)
[Update]
Looks like Koala returns an array of string-based Hashes, so you won't be able to use collect(&:id)
to get the IDs. Here's what I used to get the array of IDs on the console (sensitive data masked, obviously):
pry(main)> oauth = Koala::Facebook::OAuth.new 'xxxxxxx', 'yyyyyyyyy'
=> #<Koala::Facebook::OAuth:0x00000100d03be8>
pry(main)> token = 'zzzzzzzzzz'
=> "zzzzzzzzzz"
pry(main)> graph = Koala::Facebook::GraphAPI.new token
=> #<Koala::Facebook::GraphAPI:0x00000100ce3ac8>
pry(main)> friends = graph.get_connections "me", "friends"
=> [{"name"=>"A Friend", "id"=>"An ID"}, {"name"=>"Another Friend", "id"=>"Another ID"}]
uids = friends.collect { |f| f["id"] }
=> ["An ID", "Another ID"]
Also, if you're following Rails conventions, the id
field of your Services
table is going to be the primary key of the record, and not the Facebook ID of the service user, so you may need to query on another field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With