Ruby on rails 基于外键数的ActiveRecord作用域

Ruby on rails 基于外键数的ActiveRecord作用域,ruby-on-rails,ruby,rails-activerecord,arel,Ruby On Rails,Ruby,Rails Activerecord,Arel,举一个典型的例子: class Post < ActiveRecord::Base has_many :comments end class Comments < ActiveRecord::Base belongs_to :post end 我知道这可以在Ruby中通过一个简单的Enumerableselect来完成。最好在数据库上进行计算,因为实际上只有一个模型满足谓词。这个范围如何: scope :quiet, ->(n) { where("(SELECT C

举一个典型的例子:

class Post < ActiveRecord::Base
  has_many :comments
end

class Comments < ActiveRecord::Base
  belongs_to :post
end
我知道这可以在Ruby中通过一个简单的Enumerableselect来完成。最好在数据库上进行计算,因为实际上只有一个模型满足谓词。

这个范围如何:

scope :quiet, ->(n) { where("(SELECT COUNT(*) FROM comments WHERE post_id = `posts`.id) < ?", n) }

它将在所有数据库端完成。它不使用join,因此如果需要,您可以实际更新这些日志记录。

您可以这样做

Post.joins(:comments).group("posts.id HAVING count(comments.id) > 0")

这不是完全的阿雷尔,但它肯定会工作

拥有是我一直在寻找的!整个阿雷尔集团…拥有。。。代码极其冗长,几乎没有额外的好处。
Post.joins(:comments).group("posts.id HAVING count(comments.id) > 0")