【问题标题】:How to get the highest association in a record如何获得记录中的最高关联
【发布时间】:2015-04-14 08:25:20
【问题描述】:

我目前有一个具有 Post 类的 Rails 应用程序。发布 belongs_to 用户。

如何获得发帖次数最多的前 3 名用户?我猜它在某个地方

 Post.all.users.(do something here to get the user count and know who are the top 3

好吧,只是一个更新,因为 .all 可能会令人困惑。在某些情况下,我需要在某一天获得顶级用户,所以就像

Post.today.get_top_users

我的问题是如何获得顶级用户。

【问题讨论】:

  • 你可能会喜欢这个答案:stackoverflow.com/a/26542539/1942551
  • 嗨 @karlingen 是的,我前一阵子看到了,所以我更新了我的问题,因为我的问题不会获得顶级用户,而是特定日期。

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


【解决方案1】:

我是这样做的。

User.joins(:posts).select("COUNT(posts.id) as posts_count, users.*").group('users.id').order('posts_count DESC').where('Date(posts.created_at) = ?', Date.today).limit(3)

【讨论】:

  • 还有.limit(3) 这是我的最爱
  • 但是我只会查看某一天的帖子,所以我需要在帖子上指定日期。
【解决方案2】:

试试这个 编辑

User.select('users.*, count(posts.id) AS posts_count').joins(:posts).where('posts.created_at = ?', Time.now).group('users.id').order('posts_count DESC').limit(3)

使用counter_cache 会更快。定义一个类方法 将counter_cache: true 添加到model

def self.get_top_users
    select('users.*, COUNT(posts.id) AS posts_count')
      joins(:users).where('posts.created_at = ?', Time.now).                                                  
      group('users.id').
      order('posts_count DESC').
      limit(5)
end

那你就可以打电话了

Post.get_top_users

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 2013-01-05
    • 2011-05-09
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多