2010-10-15 40 views
1

我正在研究社交網絡應用程序,並試圖構建 複雜的查詢,該查詢有效地將所有用戶的朋友的登錄信息從 數據庫。基本上我需要:使用複雜的Rails 3查詢(需要:user.friends.checkins)

我重新創建(以簡化形式)下面的數據結構 參考,幷包含了多種解決方案,我發現「user.friends.checkins」,但是我覺得 喜歡我的解決方案子最佳。我希望有人能出來 一個更好的辦法......所以這裏有雲:

我想這第一次,它的工作原理,但太慢給用戶 通常每個+1000朋友:

=> Checkin.where(:user_id => self.friends) 

然後我想這一點,也可以工作,是要快得多,但感覺 馬虎:

=> Checkin.joins(:user).joins('INNER JOIN "friendships" ON 
"users"."id" = "friendships"."friend_id"').where(:friendships => 
{:user_id => 1}) 

任何幫助,您可以提供將不勝感激!感謝 提前!

===數據結構===

Users table has columns: id, name 
Friendships table has columns: user_id, friend_id 
Checkins table has columns: id, location, user_id 

===模型===

class User 
has_many :friendships 
has_many :friends, :through => :friendships 
has_many :checkins 
end 

class Friendship 
belongs_to :user 
belongs_to :friend, :class_name => 'User' 
end 

class Checkin 
belongs_to :user 
end 

回答

0

最好的解決辦法:

Checkin.joins(:user => :friendships).where('friendships.friend_id' => self.id) 
0

第一個查詢應該爲你服務好。將索引添加到查詢中的外鍵字段。到目前爲止,我已經找到

+0

與第一解決方案的問題在於,它需要3秒鐘的加載由「self.friends」返回500-1000 ActiveRecord對象。它不是SQL很慢(SQL只需要2-3ms),它是ActiveRecord。我剛剛發佈了另一個解決方案,我發現這似乎是一種改進。 – 2010-10-15 07:24:48