Rails:此 SQL 查询被多次调用,我已针对预加载进行了优化

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

我在 rails 简单的 activerecord 查询中看到了上述问题

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

这两个查询都不是任何其他查询的一部分,这意味着不包含在任何 join/includes 查询中。但是独立查询为什么会出现这个问题?

仅仅因为一个操作被多次调用各种输入不能被称为N+1查询问题。

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)}

警告正确!如果您的数组中有 27 个项目,它将调用 DB 27 次!

如何解决?我有下一个建议:

    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