How to optimize this query in ActiveRecord - latest 10 topics by friends

岁酱吖の 提交于 2020-01-06 20:01:35

问题


User model:

 user_id  phone_no
 -------  --------
   1      555-0001
   2      555-0002
   .
   .

Every user has his/her own phone number.

Friend model:

 user_id  phone_no
 -------  --------
  user 1  555-0002
  user 1  555-0003
  user 2  555-0001
  user 2  555-0004

User may has many phones numbers. A phone number match is consider as a friend (one direction), e.g. owner of 555-0003 is a friend of user 1, not vise versa.

Topic model:

  topic_id  user_id  title
  --------  -------  -----
      1        1     Hello
      2        1     Hi

How to optimize the query of getting the latest 10 topics by friends of a user?

I tried something like:

user = User.find(2) # any user
phones = Friend.all(:conditions=>['user_id = ?',user.id],:select=>'phone_no').map {|x| x.phone_no}
friends = User.all(:conditions=>['phone_no in (?), phones]).map {|x| x.user_id}
topics = Topic.all(:conditions=>['user_id in (?), friends], :limit => 10, :order => 'updated_at DESC')

but worried about performance when breaking up queries. How can I optimize this ActiveRecord query?


回答1:


class User
  has_many :topics
  has_many :friends
  has_many :friend_users, :through => :friends
  has_many :friend_topics, :through => :friend_users, :source => :topics      
end

class Friend
  belongs_to :user
  belongs_to :friend_user, :class_name => "User", :foreign_key => :phone_no, 
                :primary_key  => :phone_no
end

class Topic
  belongs_to :user
end

Now given a user you can get the friend topics as follows:

current_user.friend_topics.limit(10)

Make sure you add

  • an unique index on the phone_no col in the User class
  • an index on the phone_no col in the Friend class.


来源:https://stackoverflow.com/questions/11151243/how-to-optimize-this-query-in-activerecord-latest-10-topics-by-friends

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