0

ユーザーのリストがあるrailsアプリがあります。私はユーザー間でさまざまな関係を持っています。たとえば、一緒に仕事をしている、友達、優先しているなどです。ユーザーを一覧表示するとき、現在のユーザーが特定のユーザーを友達に追加できるかどうかを判断する必要があります。

     -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(user)は次のようになります。

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

私の問題は、これは私の場合、ユーザーごとに4つのクエリを意味することです。リスト10のユーザーは40のクエリを意味します。どういうわけかこれを熱心にロードできますか?

4

1 に答える 1

0

取得random_userscurrent_user
たのでnon_firends = random_users - current_user.freindships、2つのクエリでユーザークエリからのすべてのnon_friendsを返します。

実際には、すべての友達をプリロードしてinclude?、友情配列のメソッドを使用できます。

@friendships = current_user.friendships

def can_request_friendship_with(user)
  !self.eql?(user) && @friendships.include? user
end
于 2010-05-10T12:16:06.070 に答える