Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Last active September 19, 2020 05:09
Show Gist options
  • Save inopinatus/d87bedd78f248a0619754422f9495dcf to your computer and use it in GitHub Desktop.
Save inopinatus/d87bedd78f248a0619754422f9495dcf to your computer and use it in GitHub Desktop.
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