【问题标题】:Order posts by most comments按大多数评论排序帖子
【发布时间】:2014-09-24 07:54:40
【问题描述】:

Userhas_many Post.

Posthas_many Comment.

如何查询用户的帖子,按每个帖子的 cmets 数量排序?

非常感谢尽可能多的 ActiveRecord 式答案。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-4


    【解决方案1】:

    将帖子的 cmets 计数存储为 counter_cacheComment 模型中:

    belongs_to :post, counter_cache: true
    

    然后在您的 posts 表中,有一个 comments_count 字段,它是一个整数。

    从那里开始,很容易:

    Post.order("comments_count DESC")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      相关资源
      最近更新 更多