Rails Active Record: How to reduce number of trips to database?

痞子三分冷 提交于 2019-12-10 21:03:36

问题


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:

  1. This hits the database once per friend. So in my case there are a total of 582 queries executed.

  2. 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]) } 

回答1:


I think this should work

friend_ids = @fb_friends.map(&:id)
authorizations = Authorization.where('provider = ? AND uid IN (?)','facebook',friend_ids)
@fb_friends_on_cody = authorizations.map(&:user_id)
@fb_friends.delete_all('id in (?)', @fb_friends_on_cody)


来源:https://stackoverflow.com/questions/11676760/rails-active-record-how-to-reduce-number-of-trips-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!