[英]How to iterate through two grouped queries to display both in a single per-month table
在Rails 3.2應用程序中,我有一個“儀表盤”視圖,該視圖匯總了多個模型的記錄。 對於其中兩個模型-我們將其稱為“動作”和“事件”-我想在一個表中顯示每月的歷史計數。 換句話說,輸出將類似於:
Action Event
Jan 2 4
Feb 7 1
Mar 5 2
我了解如何針對單個查詢實現此目的,但是由於在循環查詢中的記錄時添加了tr
標記,因此我看不到如何將兩者結合在一起。 有沒有簡單的方法可以實現這一目標,還是應該尋找更簡單的替代方法?
#controller
class DashboardController
def dashboard
@actions = Action.all.group_by { |a| a.date_created.beginning_of_month }
@events = Event.all.group_by { |e| e.date_created.beginning_of_month }
end
end
#view
<table>
<tr>
<th>Month</th>
<th>Actions</th>
<th>Events</th>
</tr>
#this correctly summarizes actions by month
#how do I add events to this table?
<% @actions.sort.each do |month, actions| %>
<tr>
<th><%= month.strftime('%B') %></th>
<td><%= actions.count %></td>
</tr>
<% end %>
</table>
您可以為數據使用包裝器,這樣可以得到一個數組
@data = []
(@actions.keys + @events.keys).uniq.sort.each { |month|
data << { month: month, action: @actions[month].try(:length) || 0, event: @events[month].try(:length) || 0 }
}
會給你帶來大量的哈希值
[ { month: 'Jan', actions: 2, events: 4}, { month: 'Feb', actions: 12, events: 14}]
您可以在其上輕松進行迭代。
或者您可以迭代(@ actions.keys + @ events.keys),然后執行
<th><%= key.strftime('%B') %></th>
<td><%= @actions[key].count %></td>
<td><%= @events[key].count %></td>
嘗試使用zip
方法合並兩個數組:
<% @actions.sort.zip(@events.sort).each do |action_group, event_group| %>
<tr>
<th><%= action_group.first.strftime('%B') %></th>
<td><%= action_group.last.count %></td>
<td><%= event_group.last.count %></td>
</tr>
<% end %>
文件在這里: http : //www.ruby-doc.org/core-2.1.0/Array.html#method-i-zip
需要注意的是,每個月都必須同時存在動作和事件,否則兩個數組將具有不同數量的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.