posts table
int id
comments table
int id
int post_id
datetime created_at
i need to orde开发者_如何学运维r posts by post's comments created_at. I tried something like that but i can't select distinct post ids.Any help will be appreciated.
Post.all(:joins => :comments, :order => 'comments.created_at')
I want to see the post which was commented lately at the top.
The condition you are passing is invalid.
The easiest way you can accomplish what you are trying to do, is by adding a column to your posts table - say last_commented_at
.
In your Comment
model you add a callback
class Comment < ActiveRecord::Base
belongs_to :post
after_save :update_posts_last_commented_attribute
def update_posts_last_commented_attribute
post.update_attribute(:last_commented_at, updated_at)
end
end
Then you can load your Posts by calling
Post.order("last_commented_at DESC" )
to show the posts first, that have recently been commented.
精彩评论