简体   繁体   English

渴望加载此Rails关联

[英]Eager load this rails association

I have rails app which has a list of users. 我有有用户列表的Rails应用程序。 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: can_request_friendship_with(user)看起来像:

  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. 我的问题是,在我的情况下,这意味着每个用户4个查询。 Listing 10 users means 40 query. 列出10个用户意味着40个查询。 Could i somehow eager load this? 我能以某种方式渴望加载吗?

Let's we have got random_users and current_user 让我们有random_userscurrent_user
so non_firends = random_users - current_user.freindships will return in two queries all non_friends from users query. 因此non_firends = random_users - current_user.freindships将在两个查询中返回用户查询中的所有non_friends。

Actually you can preload all your friends and use include? 实际上,您可以预载所有朋友并使用include? method for friendships Array: 友谊数组的方法:

@friendships = current_user.friendships

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM