Last active
August 21, 2018 09:15
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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