【发布时间】:2023-04-08 19:37:02
【问题描述】:
我想为所有没有 cmets 的帖子创建一个范围...我不明白如何在模型中(通过创建范围)检查我的帖子是否附有任何评论,因为只有评论似乎知道他们属于哪个帖子,而不是帖子知道评论属于它。
Post
has_many :comments
Comments
belong_to :post
(如果我错了,请阻止我。)
【问题讨论】:
标签: ruby-on-rails-3 scope rails-models
我想为所有没有 cmets 的帖子创建一个范围...我不明白如何在模型中(通过创建范围)检查我的帖子是否附有任何评论,因为只有评论似乎知道他们属于哪个帖子,而不是帖子知道评论属于它。
Post
has_many :comments
Comments
belong_to :post
(如果我错了,请阻止我。)
【问题讨论】:
标签: ruby-on-rails-3 scope rails-models
用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
【讨论】: