2013-10-10 5 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 개 보고서가 전송 될 것이다 :

내가 설명되지 않을 수도 있습니다 아주 잘 설명해 주어야겠습니까?

당신은 정기적 GROUP_BY 이것을 달성 할 수
+0

'알림 '이 다른 모델에 어떻게 맞습니까? – dax

+0

질문 has_many 알림 및 알림 belongs_to 질문 – Shpigford

답변

1

이 같은

@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].com">], 
    [<Notification id: 3 frequency: "daily", email "[email protected]">], 
    [<Notification id: 4 frequency: "monthly", email "[email protected]">,<Notification id: 5 frequency: "monthly", email "[email protected]">], 
] 
관련 문제