【问题标题】:How to group by first created_at?如何按第一个 created_at 分组?
【发布时间】:2016-11-19 13:53:38
【问题描述】:

我有一个名为 Posts 的模型,由用户创建。每个帖子都有一个 created_at 属性。我想知道从开始日期到结束日期的每个日期有多少用户第一次发帖。

我试图得到这样的结果:

1/1/2016: 15 posted for the first time
2/1/2016: 4 posted for the first time
3/1/2016: 0 posted for the first time
...

使用 ActiveRecord 有效执行此操作的最佳方法是什么? :)

【问题讨论】:

  • 你用的是什么数据库?
  • 你不能只使用 created_at,它是一个时间戳,你必须使用一个范围......

标签: ruby-on-rails ruby activerecord


【解决方案1】:

您应该做的第一件事是获取帖子的创建日期_at

class Post < ActiveRecord::Base
  ...
  def created_at_date 
    created_at.to_date
  end
  ...
end

现在您在 post 类中拥有该方法,您现在可以访问它

class User < ActiveRecord::Base
  ...
  def get_first_post_created_at
    posts.first. created_at_date
  end
  ...
end

现在能做的最后一件事就是我们的组 by get_first_post_created_at

class User < ActiveRecord::Base
  ...
  def self.group_by_first_post_created
    User.all.group_by(&:get_first_post_created_at)
  end
  ...
end

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 2020-07-31
    相关资源
    最近更新 更多