Last active
September 19, 2020 05:09
-
-
Save inopinatus/d87bedd78f248a0619754422f9495dcf to your computer and use it in GitHub Desktop.
preloading the latest of an associated collection
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
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