Skip to content

Instantly share code, notes, and snippets.

@mrbrdo
Created September 25, 2013 15:44
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 mrbrdo/6701606 to your computer and use it in GitHub Desktop.
Save mrbrdo/6701606 to your computer and use it in GitHub Desktop.
has_one :display_gallery_item, as: :imageable, class_name: "GalleryItem"
class ServiceCenterPreloader
class GalleryItemPreloader < ActiveRecord::Associations::Preloader::HasOne
def initialize(owners, reflection)
super(GalleryItem, owners, reflection, ActiveRecord::Relation.new(nil, nil))
end
private
def build_scope
t = klass.table_name
distinct = "#{t}.imageable_id, #{t}.imageable_type"
scope = super
scope.select_values = ["DISTINCT ON(#{distinct}) #{t}.*"]
scope.order(distinct)
end
end
def self.preload(service_centers)
records = Array.wrap(service_centers.to_a).compact.uniq
reflection = ServiceCenter.reflections[:display_gallery_item]
GalleryItemPreloader.new(records, reflection).run
end
end
service_centers = ServiceCenter.all.to_a
ServiceCenterPreloader.preload(service_centers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment