cross model scoping - rails 3
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.)
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
精彩评论