RailsCase29 group_by Month 分組函數group_by

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.