Skip to content

Instantly share code, notes, and snippets.

@vkuznetsov
Last active September 18, 2015 08:13
Show Gist options
  • Save vkuznetsov/b36444692b2f7acacbdd to your computer and use it in GitHub Desktop.
Save vkuznetsov/b36444692b2f7acacbdd to your computer and use it in GitHub Desktop.
module Preloading
def preload(records, association_name, preload_scope)
return records if records.blank?
reflection = records.first.association(association_name).reflection
if reflection.through_reflection
grouped_scope = reflection.through_reflection.klass.where(reflection.foreign_key => preload_scope).
includes(reflection.source_reflection_name).
each_with_object({}) do |r, hash|
if reflection.collection?
(hash[r[reflection.through_reflection.foreign_key]] ||= []) << r.association(reflection.source_reflection_name).target
else
hash[r[reflection.through_reflection.foreign_key]] = r.association(reflection.source_reflection_name).target
end
end
our_table_key = reflection.association_primary_key
elsif reflection.belongs_to?
our_table_key = reflection.foreign_key
grouped_scope = preload_scope.where(id: records.map { |r| r[our_table_key] }).index_by(&:id)
else
our_table_key = reflection.association_primary_key
if reflection.collection?
grouped_scope = preload_scope.where(reflection.foreign_key => records).group_by { |r| r[reflection.foreign_key] }
else
grouped_scope = preload_scope.where(reflection.foreign_key => records).index_by { |r| r[reflection.foreign_key] }
end
end
records.each do |record|
binding.pry if association_name == :images
association = record.association(association_name)
association.target = grouped_scope[record[our_table_key]]
association.target ||= [] if reflection.collection?
association.loaded!
end
records
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment