Created
September 25, 2013 15:44
-
-
Save mrbrdo/6701606 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
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