I have rails app which has a list of users. I have different relations between users, for example worked with, friend, preferred. When listing the users i have to decide if the current user can add a specific user to his friends.
-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)
The can_request_friendship_with(user) looks like:
def can_request_friendship_with(user)
!self.eql?(user) && !self.friendships.find_by_friend_id(user)
end
My problem is that this means in my case 4 query per user. Listing 10 users means 40 query. Could i somehow eager load this?
Let’s we have got
random_usersandcurrent_userso
non_firends = random_users - current_user.freindshipswill return in two queries all non_friends from users query.Actually you can preload all your friends and use
include?method for friendships Array: