开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜