Using Rails 3, this scope works as would be expected:
scope :with_posts, lambda {
joins(:posts).
select("authors.*, count(posts.id) posts_count").
group("posts.author_id").
having("posts_count > 0")
}
The generated SQL is:
SELECT authors.*, count(posts.id) posts_count FROM `authors` INNER JOIN `posts` ON `posts`.`author_id` = `author`.`id` GROUP BY posts.author_id HAVING posts_count > 0
But its inverse returns no results:
scope :with_posts, lambda {
joins(:posts).
select("authors.*, count(posts.id) posts_count").
group("posts.author_id").
having("posts_count < 1")
}
I'm assuming that authors with zero posts are simply not being selected by line three... so what is the solution?