【发布时间】:2014-09-24 07:54:40
【问题描述】:
Userhas_many Post.
Posthas_many Comment.
如何查询用户的帖子,按每个帖子的 cmets 数量排序?
非常感谢尽可能多的 ActiveRecord 式答案。
【问题讨论】:
标签: ruby-on-rails ruby activerecord ruby-on-rails-4
Userhas_many Post.
Posthas_many Comment.
如何查询用户的帖子,按每个帖子的 cmets 数量排序?
非常感谢尽可能多的 ActiveRecord 式答案。
【问题讨论】:
标签: ruby-on-rails ruby activerecord ruby-on-rails-4
将帖子的 cmets 计数存储为 counter_cache 在 Comment 模型中:
belongs_to :post, counter_cache: true
然后在您的 posts 表中,有一个 comments_count 字段,它是一个整数。
从那里开始,很容易:
Post.order("comments_count DESC")
【讨论】: