Skip to content

Instantly share code, notes, and snippets.

@Hampei
Last active August 21, 2018 09:15
Show Gist options
  • Save Hampei/61e5f84cc9bf5bc777a958835a3691de to your computer and use it in GitHub Desktop.
Save Hampei/61e5f84cc9bf5bc777a958835a3691de to your computer and use it in GitHub Desktop.
How to preload associations of an association that is actually cached in the association_cache
# Using measurement.measured_questionnaires.preload(:questionnaire) would lead to reloading
# both the measured_questionnaires and the questionnaires each time you call it,
# requiring a explicit memoization somewhere which could go out of sync.
# usage: measurement.measured_questionnaires.with_questionnaires.map { ... }
class Measurement < ActiveRecord::Base
has_many :measured_questionnaires, -> { order(:position) } do
def with_questionnaires
ActiveRecord::Associations::Preloader.new.preload(self, :questionnaire)
self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment