I have an Array if a user’s Facebook friend list as follows:
[
{ 'name' => 'John Mallock', 'id' => '123123' },
{ 'name' => 'Susan Freely', 'id' => '123123123' },
...
]
I’d like to filter this list for entries that exist in the users table in my Rails app. I’m currently doing this as follows:
graph = Koala::Facebook::API.new 'access_token'
friends = graph.get_connections 'me', 'friends' # Returns the structure above
friends.select! { |f| User.exists? :facebook_id => f['id'] }
This results in a SELECT query for every friend in the list, which is noticeably inefficient.
Is there a more effective means of filtering this list based on database records?
Probably the simplest way to do this is to pass an array into a
wheremethod in ruby. If you pass in an array, it will be converted into aINquery on the database:If you need to know which entries in
friendscorrespond to users, you could then call a select on friends:Note that the above is pretty inefficient if you have a decent amount of records in either array. You’d probably want to optimize it somewhat, or better yet, don’t use the friends array and just iterate over User records if they contain the same data.