2012-05-15 80 views
4

以標準NewsFeed模式(id,user_id)如何編寫一個按月返回計數的rails查詢?

如何查詢NewsFeed模型中每月的記錄數量,然後排除少數user_id?

結果將產生:

Jan - 313 
Feb - 3131 
Mar - 44444 
etc... 

有一個簡單的方法與軌做到這一點還是需要編寫每月的查詢?

感謝

回答

3

有在活動記錄 可用,所以你可以做同樣的事情到

NewsFeed.count(:group=>"date_trunc('month', created_at)",:conditions=>"user_id NOT IN (?)",[exluded_ids]) 
+0

的錯誤W¯¯PG ::錯誤:錯誤:列「月」不存在 – AnApprentice

+0

我已經改變了例子有點 –

+0

謝謝,但該錯誤:的ActiveRecord :: StatementInvalid:PG ::錯誤:錯誤:列「news_feeds.created_at」必須出現在GROUP BY子句中,或者用於聚合函數 – AnApprentice

1

http://railscasts.com/episodes/29-group-by-month

NewsFeed.where("user_id is not in (?)",[user_ids]).group_by { |t| t.created_at.beginning_of_month } => each {|month,feed| ...} 

NewsFeed.select("*,MONTH(created_at) as month").where("user_id is not in (?)",[user_ids]).group("month") => ... 
+1

StatementInvalid:PG :: Error:ERROR:function month(timestamp without time區域)不存在 – AnApprentice

2

數和組語句也許這將工作:

monthly_counts = NewsFeed.select("date_trunc('month', created_at) as month, COUNT(id) as total").where("user_id NOT IN (?)",[exluded_ids]).group("month") 
monthly_counts.each do |monthly_count| 
    puts "#{monthly_count.month} - #{monthly_count.total}" 
end 
8

在Rails 4中,執行此操作的方法是在模型上創建範圍。

class NewsFeed < ActiveRecord::Base 
    scope :group_by_month, -> { group("date_trunc('month', created_at) ") } 
    scope :exclude_user_ids, -> (ids) { where("user_id is not in (?)",ids) } 
end 

然後你會說它是這樣的:

@counts = NewsFeed.exclude_user_ids(['1','2']).group_by_month.count 

這會給你:

{2014-01-01 00:00:00 UTC=>313, 2014-02-01 00:00:00 UTC=>3131} 

然後你輸出(HAML):

- @counts.each do |m| 
    = "Month: #{m[0].strftime("%b")}, Count: #{m[1]}" 

哪會導致:

Month: Jan, Count: 313 
Month: Feb, Count: 3131 
相關問題