I’ve following models
Post:
has_many :comments
Comment:
belongs_to :post
and a controller called pages with following code in it.
def home
@posts = Post.includes(:comments)
respond_to do |format|
format.html
end
end
So say if I’ve 3 posts P1, P2, P3; initially rendered in same order on home page. Later if P2 gets commented and I refresh the page the order should be P2, P1, P3. So whenever a post gets commented it should appear on top. All the posts should be sorted in descending order of time they get commented. How can I achieve this?
My attempt – What I tried is very inefficient and definitely not a good practice. I get unique post_ids from comments in descending order and using the post_ids get the posts.
I’m sure rails provides best way to do it. Help highly appreciated. Thanks.
Try this,