kotu b
kotu b

Reputation: 333

Rails: This SQL query was called multiple times and my be opthimised for eager loading

enter image description here

I am seeing the above issue in rails simple activerecord query

where(email:email).first_or_create!
find_or_create_by!(phone_number: phone_number)

Both these queries are not part of any other query meaning not included in any join/includes query. But for an independent query why this issue is coming?

Just because an operation is called multiple times with various inputs can not be called as N+1 query issue.

def email_address(email)
  email = email.downcase
  begin
    where(email:email).first_or_create!
  rescue ActiveRecord::RecordNotUnique
    find_by_email(email)
  end
end

Assume that the method was called [arry_of_emails].map {|x| email_address(x)}

Upvotes: 0

Views: 662

Answers (1)

kunashir
kunashir

Reputation: 959

The warning was correct! If you have 27 items in your array it will call DB 27 times!

How we can solve it? I have the next suggestion:

    addresses = Address.where(email: params[:emails]) #load all addresses in one request
    list = addresses.inject({}) { |memo, adr|  memo[adr.email] = adr; memo }
    params[:emails].each do |email|
      # if an address is not in our list create new
      Address.create(email: email) unless list.keys?(email)
    end

Upvotes: 1

Related Questions