I have a a Comments table and a Posts table, where a Post has many comments and a comment belongs to a post (i.e. it has a post_id in the table).
How can I efficiently select the last ten Posts that DO NOT have comments.
I can’t seem to accomplish this without first selecting all the posts and checking each for a 0 comment count.
Thanks in advance for any help.
-Nathan
You can add a counter cache to the
Commentmodel and a couple of named scopes to thePostmodel. Something like:If you’re using Rails 3 then the named scope syntax is a little different:
Now you can find posts without any comments by chaining the named scopes together:
If you wanted to get all the posts without any comments (i.e. not just the ten most recent posts), then it would be:
—You may have noticed that in the Rails 3 example I included the
poststable name in the:recentscope. This is a good practice to get in to so that you avoid ambiguous column names in SQL queries if two tables have the same column name. This Railscast explains more.