Skip to content

Instantly share code, notes, and snippets.

@mrbrdo
Last active December 23, 2015 22:08
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/6700690 to your computer and use it in GitHub Desktop.
Save mrbrdo/6700690 to your computer and use it in GitHub Desktop.
class Person < ActiveRecord::Base
has_many :photos
has_one :display_photo, -> {
self.select_values = ["DISTINCT ON(photos.person_id) photos.*"]
order('photos.person_id')
}, class_name: "Photo"
end
# Polymorphic association example
class Person < ActiveRecord::Base
has_many :photos, as: :photo_parent
has_one :display_photo, -> {
fields = "photos.photo_parent_id, photos.photo_parent_type"
self.select_values = ["DISTINCT ON(#{fields}) photos.*"]
order(fields)
}, as: :photo_parent, class_name: "Photo"
end
people = Person.all.includes(:display_photo)
people.each { |person| puts person.display_photo.id }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment