views:

65

answers:

1

Hi, 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?

A: 

Let's we have got random_users and current_user
so non_firends = random_users - current_user.freindships will return in two queries all non_friends from users query.

Actually you can preload all your friends and use include? method for friendships Array:

@friendships = current_user.friendships

def can_request_friendship_with(user)
  !self.eql?(user) && @friendships.include? user
end
fl00r
Your solution is not the best, but the idea behind it is good. In can_request_friendship_with function we cannot access that instance variable, but that's not a problem.
dombesz
It's wasn't a complete solution. What I was talking about is excluding your problem from db level
fl00r