I have a rails 3.1 app with the following Models:
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
I want to retrieve 5 posts, with the most recent comments.
Problem is that when for example Post A has 3 comments that are more recent than the most recent comment on Post B.
I want the query to do something like this:
The number on the comments means 1 = newest 10 = oldest.
Post A
comment 1 #=>ok fetch the post
Post B
comment 2 #=>ok fetch the post
comment 3 #=>this post is fecthed go on find the next one
comment 4 #=>this post is fecthed go on find the next one
Post C
comment 5 #=>ok fetch the post
comment 6 #=>this post is fecthed go on find the next one
Post D
comment 7 #=>ok fetch the post
comment 8 #=>this post is fecthed go on find the next one
Post E
comment 9 #=>ok fetch the post
comment 10
Is it possible to make a elegant query to do this?
A possible solution is to update a :comment_updated_at column in the post table.
This should works:
This will return 5 last comments, with distinct posts.
So after that you can just:
and voila.