2016-11-19 18 views
0

我有一个模型叫用户创建的帖子。每篇文章都有一个created_at属性。我想知道从开始日期到结束日期的每个日期第一次发布的用户数。如何通过第一个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有效地做到这一点,最好的方法是什么? :)

+0

什么数据库你使用的是? –

+0

你不能只使用created_at,它是一个时间戳,你将不得不使用范围... – MageeWorld

回答

0

,你应该做的第一件事就是获得那个职位的日期created_at

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

现在,你必须在后类方法,你现在可以访问它

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

现在可以做的最后一件事是我们小组通过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 

我希望塔这是能够帮助你:)

相关问题