1
我想为所有帖子创建一个范围没有评论...我不明白如何,在模型(通过创建范围),我可以检查我的帖子是否有任何评论附加到因为只有评论似乎知道他们属于哪个帖子,而不是知道帖子属于哪个帖子。跨模型范围 - 轨道3
Post
has_many :comments
Comments
belong_to :post
(请阻止我,如果我错了)
我想为所有帖子创建一个范围没有评论...我不明白如何,在模型(通过创建范围),我可以检查我的帖子是否有任何评论附加到因为只有评论似乎知道他们属于哪个帖子,而不是知道帖子属于哪个帖子。跨模型范围 - 轨道3
Post
has_many :comments
Comments
belong_to :post
(请阻止我,如果我错了)
与SQL
Post.includes(:comments).where("comments.id is NULL")
所以范围
scope :without_comments, includes(:comments).where("comments.id is NULL")
不过还好在这里使用counter_cache
:http://railscasts.com/episodes/23-counter-cache-column