2010-05-10 75 views
0

我有導軌應用程序,其中有一個用戶列表。我有不同的用戶之間的關係,例如,與朋友合作,首選。在列出用戶時,我必須決定當前用戶是否可以將特定用戶添加到他的朋友。急切加載此導軌協會

 -if current_user.can_request_friendship_with(user) 
     =add_to_friends(user) 
    -else 
     =remove_from_friends(user) 

    -if current_user.can_request_worked_with(user) 
     =add_to_worked_with(user) 
    -else 
     =remove_from_worked_with(user) 

的can_request_friendship_with(用戶)看起來像:

def can_request_friendship_with(user) 
    !self.eql?(user) && !self.friendships.find_by_friend_id(user) 
    end 

我的問題是,這意味着我的每用戶案例4查詢。清單10的用戶意味着40個查詢。我可以不知何故加載這個?

回答

0

讓我們有random_userscurrent_user
所以non_firends = random_users - current_user.freindships將在兩個查詢返回的用戶查詢中的所有non_friends。

其實你可以下載所有的朋友和使用include?方法友誼陣列:

@friendships = current_user.friendships 

def can_request_friendship_with(user) 
    !self.eql?(user) && @friendships.include? user 
end 
+0

您的解決方案是不是最好的,但它背後的想法是好的。在can_request_friendship_with函數中,我們無法訪問該實例變量,但這不是問題。 – dombesz 2010-05-10 17:19:54

+0

這不是一個完整的解決方案。我在說的是從數據庫級別排除你的問題 – fl00r 2010-05-10 17:34:36