admin: always eager load the user relationship

Now that `Administrateur.email` is merely an alias to
`administrateur.user.email`,
and we changed every occurence of `administrateurs.pluck(:email)` to
`administrateurs.map(&:email)`, the new version using `map` may cause N+1
queries if the users have not been preloaded.

  It makes sense to always preload the user when fetching an
  Administrateur:

  - Administrateur and User have a strongly coupled relationship
  - It avoids N+1 queries everywhere in the app

  Of course fetching an administrateur without needing its user will now do
  an unecessary fetch of the associated user. But it seems better than
  leaving a risk of N+1 queries in many places.
This commit is contained in:
Christophe Robillard 2020-02-03 13:44:12 +01:00
parent 4a1980e95a
commit 91f1722088

View file

@ -9,11 +9,13 @@ class Administrateur < ApplicationRecord
has_one :user, dependent: :nullify
default_scope { eager_load(:user) }
scope :inactive, -> { joins(:user).where(users: { last_sign_in_at: nil }) }
scope :with_publiees_ou_closes, -> { joins(:procedures).where(procedures: { aasm_state: [:publiee, :close, :depubliee] }) }
def self.by_email(email)
Administrateur.eager_load(:user).find_by(users: { email: email })
Administrateur.find_by(users: { email: email })
end
def email