根据孩子的数量排序

时间:2011-03-21 09:26:19

标签: ruby-on-rails ruby ruby-on-rails-3 associations

我想通过帖子评论计数。但是这段代码不起作用。任何帮助将不胜感激。

模特邮报

has_many :comments
scope :active, where("active = ?", true)  
scope :popular, active.limit(10).sort { |a, b| b.comments.size <=> a.comments.size }

模特评论

belongs_to :post

1 个答案:

答案 0 :(得分:2)

has_many :comments
scope :active, where("active = ?", true)
scope :popular, active.joins(:comments).select("posts.*, count(posts.id) as a_c").group("comments.post_id").order("a_c DESC").limit(10)