class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
scope :recent, -> { order(‘created_at DESC’) }
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
On user’s feed page, what I am trying to do is to load posts that each post has the last 3 comments eager loaded to show to the user.
# Bad : It will load all comments from db into memory, and it filters out in ruby
Post.recent.includes(:user, :comments).limit(10)
Another way, I’m not sure it is going to work, I tried to do a custom sql, but I’m don’t know how to map them into active record objects.
SELECT posts.*, first_3_comments.*
FROM posts
LEFT OUTER JOIN (
SELECT id, body, post_id, created_at
FROM (
SELECT *, row_number() OVER (PARTITION BY comments.post_id ORDER BY comments.created_at DESC) AS row_number_x
FROM COMMENTS
WHERE (comments.post_id IN (79, 80))
) AS t1 WHERE (row_number_x <= 3)
) AS first_3_comments ON (first_3_comments.post_id = posts.id)
How do you solve this problem?