Order by association created_at, or by own created_at if no association

江枫思渺然 提交于 2019-12-12 04:46:46

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13604931/order-by-association-created-at-or-by-own-created-at-if-no-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!