Reputation: 3499
My group model has_many posts, posts have_many comments.
When I show the posts on a group, I want to order by the created at of the most recent comment, if there are any on a post, or by the created_at of the post itself.
So an old post would jump back to the top of the list if it has a new comment.
Upvotes: 0
Views: 196
Reputation: 121
You can add commented_at:datetime column into posts table, then add before_create callback to Post model:
before_create :set_default_commented_at
def set_default_commented_at
self.commented_at ||= Time.now
end
And add :touch to belongs_to association of Comment model:
belongs_to :post, touch: :commented_at
After all you'll be able to order by commented_at column.
Upvotes: 0
Reputation: 15771
I would stick to a little different approach: your Comment belongs_to :post
and belongs_to
accepts :touch
option. Set it to true
and your Post's updated_at
will be automatically updated on a Comment's modification. This way you can freely show your posts ordered by their updated_at
.
Upvotes: 4