简体   繁体   中英

Avoiding n+1 with where query active record

I'm looking at my server log and there's a lot of SELECT statements from a particular query. I'm aware of n+1 issues and this seems to be one. However I'm not sure what the solution would be for this query. Is this a single query or multiple for every user that is returned (I believe WHERE is a single query)?

User.where(profile_type: self.profile_type).where.not(id: black_list)

EDIT:

user.rb

  def suggested_friends
    black_list = self.friendships.map(&:friend_id)
    black_list.push(self.id)
    return User.where(profile_type: self.profile_type).where.not(id: black_list)
  end

index.json.jbuilder

json.suggested_friends @user.suggested_friends do |friend|
  json.set! :user_id, friend.id
  json.(friend.profile, *friend.profile.attributes.keys)
end

the issue was leaving out the includes(:profile) . Using the following query solved my problem

User.where(profile_type: self.profile_type).where.not(id: black_list).includes(:profile)

thank you for the comments to point me in the right direction

User.where(profile_type: self.profile_type).where.not(id: black_list)

Is only 1 query, even if you have multiple where clauses, rails is smart to make from it 1 sql query.

If you had

users = User.where(profile_type: self.profile_type)
users.each do |u|
   u.get_all_comments
end

This is n+1 query, because you ask for all users , then for each user you make new request for its comments , this is N (queries for comments) and 1 query for all users

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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