Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
preloading the latest of an associated collection
class Post
has_many :comments
has_one :latest_comment, -> { latest_by :post_id }, class_name: 'Comment'
class Comment
scope :latest_by, -> column {
from(
order(column, created_at: :desc).arel
.distinct_on(arel_table[column])
.as(quoted_table_name))
}
Post.preload(:latest_comment).each do |post|
puts post.latest_comment.id
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment