Created
November 3, 2018 20:03
-
-
Save ArtOfCode-/8efd6417cdad7baa7c663f9f11edbf6d to your computer and use it in GitHub Desktop.
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
class ActiveRecord::Relation | |
# Preload one level a chained association whose name is specified in attribute. | |
def preload_chain(attribute, collection: nil) | |
preloader = ActiveRecord::Associations::Preloader.new | |
preloader.preload(collection || records, attribute.to_sym) | |
self | |
end | |
# Preload all levels of a chained association specified in attribute. Will cause infinite loops if there are cycles. | |
def deep_preload_chain(attribute, collection: nil) | |
return if (collection || records).empty? | |
preload_chain(attribute, collection: collection) | |
deep_preload_chain(attribute, collection: (collection || records).select(&attribute.to_sym).map(&attribute.to_sym)) | |
self | |
end | |
# Preload one level of a chained association on a table referenced by the current table. | |
def preload_reference_chain(**reference_attribs) | |
reference_attribs.each do |t, a| | |
preload_chain(a, collection: records.map { |r| r.public_send(t.to_sym) }) | |
end | |
self | |
end | |
# Preload all levels (including infinite loops) of a chained association on a referenced table. | |
def deep_preload_reference_chain(**reference_attribs) | |
reference_attribs.each do |t, a| | |
deep_preload_chain(a, collection: records.map { |r| r.public_send(t.to_sym) }) | |
end | |
self | |
end | |
end |
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
Report.all.includes(:status, :location).deep_preload_reference_chain(location: :group).where.not(status: Status['Open']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment