Created
March 29, 2018 18:36
-
-
Save sobstel/19f40ac2141cc1db0803d360127b2945 to your computer and use it in GitHub Desktop.
Rails manual association preloading
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
# 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
what is
what_ever_you_want
referring to?