RailsCase29 group_by Month 分组函数group_by

在大多数的rails应用中,很多都涉及到分组,如task模型有due date属性,想将task按照月份进行分组,此时可使用group_by函数,下图为所有task的list。

Our tasks as a 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如下:

ruby

class TasksController < ApplicationController
  def index
    @tasks = Task.all
    @task_months = @tasks.group_by { |t| t.due_at.beginning_of_month }
  end
end

我们向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 %>


运行结果如下:

The tasks are now grouped, but the months are in the wrong order.


如果想对月份进行排序,可将代码修改为:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值