开发者

cross model scoping - rails 3

开发者 https://www.devze.com 2023-03-21 04:49 出处:网络
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

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

精彩评论

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

关注公众号