Rails 3 を使用すると、このスコープは期待どおりに機能します。
scope :with_posts, lambda {
joins(:posts).
select("authors.*, count(posts.id) posts_count").
group("posts.author_id").
having("posts_count > 0")
}
生成される SQL は次のとおりです。
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
しかし、その逆は結果を返しません。
scope :with_posts, lambda {
joins(:posts).
select("authors.*, count(posts.id) posts_count").
group("posts.author_id").
having("posts_count < 1")
}
投稿がゼロの著者は、単に 3 行目で選択されていないと思います...では、解決策は何ですか?