標籤:des http os io 使用 ar for div 代碼
在大多數的rails應用中,很多都涉及到分組,如task模型有due date屬性,想將task按照月份進行分組,此時可使用group_by函數,為所有task的list。
為了瞭解group_by函數,可先瞭解如此的命令列:
terminal>> a = (1..20).to_a=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]>> a.group_by { |num| num/5 }=> {0=>[1, 2, 3, 4], 1=>[5, 6, 7, 8, 9], 2=>[10, 11, 12, 13, 14], 3=>[15, 16, 17, 18, 19], 4=>[20]}>>
使用group_by對一個array進行分組。
其他
對於不同的rails版本,返回的內容格式可能如下:
ruby=> [[0, [1, 2, 3, 4]], [1, [5, 6, 7, 8, 9]], [2, [10, 11, 12, 13, 14]], [3, [15, 16, 17, 18, 19]], [4, [20]]]
Back To The Tasks
回到工程中,利用group_by對tasks進行分組。編輯TaskController如下:
rubyclass TasksController < ApplicationController def index @tasks = Task.all @task_months = @tasks.group_by { |t| t.due_at.beginning_of_month } endend
我們向group_by中傳入返回date所在月的第一天。
更新如下的View代碼:
ruby<% @tasks.each do |task| %><p><b><%= task.name %></b> due on <%= task.to_date.to_s(:long) %></p><% end %>
上述代碼中,tasks通過迴圈被展現出來。我們將對其進行變更,按照月份進行展現。
ruby<% @task_months.each do |month, tasks| %><h2><%= month.strftime("%B %Y") %></h2> <% tasks.each do |task| %> <p><b><%= task.name %></b> due at <%= task.due_at.to_date.to_s(:long) %></p> <% end %><% end %>
運行結果如下:
如果想對月份進行排序,可將代碼修改為:
ruby<% @task_months.keys.sort.each do |month| %><h2><%= month.strftime("%B %Y") %></h2> <% for task in @task_months[month] %> <p><b><%= task.name %></b> due at <%= task.due_at.to_date.to_s(:long) %></p> <% end %><% end %>
原文地址:http://railscasts.com/episodes/29-group-by-month?view=asciicast
RailsCase29 group_by Month 分組函數group_by