0
class Post
  has_many :commments
end

class Comment
  belongs_to :post
end

I wish to display a list of posts ordered by date of post creation (submitted_at). I also want some post xyz to appear at the top if it has some new comment posted and yet to be reviewed by moderator. We will determine this by a boolean attribute/field at comments level (moderated = 1/0)

I tried

Posts.join(:comments)
  .distinct
  .order("submitted_at DESC, comments.moderated")

but this excludes posts that have no comments and results aren't sorted as expected. I am sure that we can do this at ruby level, but looking for a way to do this using AR.

wintermeyer
  • 8,178
  • 8
  • 39
  • 85
Nirav Gandhi
  • 1,945
  • 1
  • 23
  • 32

1 Answers1

0

For the join, use this:

Posts.join("LEFT JOIN comments ON comments.post_id = posts.id")

Which will include the ones with no comments.

Your sorting seems to suggest you want a count of moderated comments, in which case, try this:

.order("submitted_at DESC, COUNT(comments.moderated)")

Although, you may need to use group in some way too.

Matt Gibson
  • 14,616
  • 7
  • 47
  • 79