Skip to content

Instantly share code, notes, and snippets.

@kidlab
Forked from sobstel/manual_preloading.rb
Created May 2, 2018 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kidlab/102dbbc4e7cfe7f540fb82e58d77d348 to your computer and use it in GitHub Desktop.
Save kidlab/102dbbc4e7cfe7f540fb82e58d77d348 to your computer and use it in GitHub Desktop.
Rails manual association preloading
# taken from https://mrbrdo.wordpress.com/2013/09/25/manually-preloading-associations-in-rails-using-custom-scopessql/
# collection association e.g. has_many
owners = People.all
association_name = :photos
owners.each do |owner|
records = Array(whatever_you_want)
association = owner.association(association_name)
association.loaded!
association.target.concat(records)
records.each { |record| association.set_inverse_instance(record) }
end
# singular association e.g. has_one
owners = People.all
association_name = :photos
owners.each do |owner|
record = whatever_you_want
association = owner.association(association_name)
association.target = record
association.set_inverse_instance(record)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment