Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
一篇文章有很多评论。我想选择所有 comments.count 大于 5 的帖子。
像这样: Post.all.joins(:comments).having("count >= 5")
如果您comments_count在 post 表中添加一列,并添加以下内容:
comments_count
class Comment < ActiveRecord::Base belongs_to :post, :counter_cache => true .. end
然后,当您保存帖子时,它将更新计数器。此时查询非常简单:
Post.where("comments_count >= ?", 5).all
或者,您可以使用纯 SQL 代码。但是,伙计,去柜台
相关:基于嵌套模型计数排序的 Rails 查询?