2016-11-19 35 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 

我希望塔這是能夠幫助你:)

相關問題