In my rails project, I have a feature that shows users whether any of their facebook friends are already on the site. After authenticating, I load their facebook friends into @fb_friends and then do this:
@fb_friends.each do |friend|
friend_find = Authorization.find_by_uid_and_provider(friend[:identifier], 'facebook')
if friend_find
@fb_friends_on_cody << friend_find.user_id
@fb_friends.delete(friend)
end
end
Basically, if a match is found (via the Authorization table), I push that record to @fb_friends_on_cody. This proves to be a very expensive operation:
This hits the database once per friend. So in my case there are a total of 582 queries executed.
Each Authorization.find_by_uid_and_provider has poor performance. I have add an index like so:
add_index "authorizations", ["uid", "provider"], :name => "index_authorizations_on_uid_and_provider", :unique => true
I imagine a lot of performance gains can be seen by addressing the first point. And perhaps there are some ways to make the query itself more efficient. Appreciate any tips on these fronts.
Solution
Using Unixmonkey's guidance, I was able to cut down the number of queries from 582 to 1! Here's the final code:
friend_ids = @fb_friends.map{|f| f[:identifier] }
authorizations = Authorization.where('provider = ? AND uid IN (?)','facebook',friend_ids)
@fb_friends_on_cody = authorizations.map{ |a| { user_id: a.user_id, uid: a.uid }}
@fb_friends.reject!{|f| @fb_friends_on_cody.map{|f| f[:uid]}.include?(f[:identifier]) }