Search code examples
ruby-on-railssortingruby-on-rails-4activerecordrails-activerecord

Rails 4: Sort by associated created_at if present, otherwise by parent's


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?


Solution

  • You can use coalesce:

    @articles = Article.includes(:comments)
                       .order('coalesce(comments.created_at, articles.created_at) desc')
                       .references(:comments)