0

User模型:

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

每个用户都有自己的电话号码。

Friend模型:

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

用户可能有很多电话号码。电话号码匹配被视为朋友(一个方向),例如所有者555-0003是 的朋友user 1,反之亦然。

Topic模型:

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

如何优化用户好友获取最近10个话题的查询?

我试过类似的东西:

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')

但在分解查询时担心性能。如何优化此 ActiveRecord 查询?

4

1 回答 1

2
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

现在给定一个用户,您可以获得朋友主题,如下所示:

current_user.friend_topics.limit(10)

确保添加

  • 类中phone_nocol的唯一索引User
  • phone_no类中col的索引Friend
于 2012-06-22T07:09:28.727 回答