I have an Article
and Comment
MVC - with the standard relationships.
I want to sort the articles in order based on the Article
created_at
, OR if the Article
has Comments
, then sort by the Comments
created_at
.
So far, I have:
@articles = Article.includes(:comments).order("comments.created_at desc")
What would I need to add to order the Article
created_at
, but only if the Article
has no comments?
You can use coalesce
:
@articles = Article.includes(:comments)
.order('coalesce(comments.created_at, articles.created_at) desc')
.references(:comments)