2013-10-10 107 views
1

我有一個notifications表,我根據他們選擇的頻率向人們發送報告。如何根據多個字段對行進行分組?

如果一個電子郵件地址存在多個questions並具有相同的frequency ...那麼我需要將它們組合在一起,這樣我就可以發送一個報告來解決這兩個問題。

[ 
    #<Notification id: 1, question_id: 58, email: "[email protected]", frequency: "daily">, 
    #<Notification id: 2, question_id: 25, email: "[email protected]", frequency: "daily">, 
    #<Notification id: 3, question_id: 47, email: "[email protected]", frequency: "monthly">, 
    #<Notification id: 3, question_id: 19, email: "[email protected]", frequency: "monthly"> 
] 

所以在我的示例數據,3份報告將發送:

我可能無法解釋這個非常好,所以讓我知道是否需要澄清。

+0

'notification'如何適合您的其他模型? – dax

+0

問題has_many通知和通知belongs_to問題 – Shpigford

回答

1

您可以用常規GROUP_BY實現這一目標:

@notifications = your_method_to_retrieve_notifications 
@notifications = @noticications.group_by do |notif| 
    notif.ferquency + ':' + notif.email 
end 

這會將您的通知是這樣的:

@notifications = { 
    'daily:[email protected]' => [<Notification id: 1>, #etc.], 
    'monthly:[email protected]' => [# list of notifications], 
    'monthly:[email protected]' => [# list of notif] 
} 

如果只想通過分組通知列表中的數組頻率&電子郵件,使用上面的方法,並添加此:

@notifications = your_method_to_retrieve_notifications 
@notifications = @noticications.group_by do |notif| 
    notif.ferquency + ':' + notif.email 
end.values 
# returns Array of arrays like: 
[ 
    [<Notification id: 1 frequency: "daily", email "[email protected]">,<Notification id: 2 frequency: "daily", email "[email protected]">], 
    [<Notification id: 3 frequency: "daily", email "[email protected]">], 
    [<Notification id: 4 frequency: "monthly", email "[email protected]">,<Notification id: 5 frequency: "monthly", email "[email protected]">], 
] 
相關問題