1

I want to create a scope for all Posts without comments... I do not understand how, in the model (by creating a scope), I can check if my Post has any Comments attached to it as only the Comments seem to know what Post they belong to, as opposed to the Post knowing what Comments belong to it.

Post
has_many :comments

Comments
belong_to :post

(Please stop me if I'm wrong.)

fighella
  • 580
  • 5
  • 16

1 Answers1

1

with sql

Post.includes(:comments).where("comments.id is NULL")

so the scope is

scope :without_comments, includes(:comments).where("comments.id is NULL")

But better to use counter_cache here: http://railscasts.com/episodes/23-counter-cache-column

fl00r
  • 82,987
  • 33
  • 217
  • 237