Rails宝典之第二十九式: group_by

这次来看active_support/core_ext/enumerable.rb里的group_by:
  #   latest_transcripts.group_by(&:day).each do |day, transcripts| 
  #     p "#{day} -> #{transcripts.map(&:class) * ', '}"
  #   end
  #   "2006-03-01 -> Transcript"
  #   "2006-02-28 -> Transcript"
  #   "2006-02-27 -> Transcript, Transcript"
  #   "2006-02-26 -> Transcript, Transcript"
  #   "2006-02-25 -> Transcript"
  #   "2006-02-24 -> Transcript, Transcript"
  #   "2006-02-23 -> Transcript"

看看视频中的例子:
class TasksController < ApplicationController
  def index
    @tasks = Task.find(:all, : order => 'due_at, id', :limit => 50 )
    @task_months = @tasks.group_by { |t| t.due_at.beginning_of_month }
  end
end

我们对@tasks的due_at.beginning_of_month做group_by,看看页面中的使用:
<h1>Tasks</h1>

<% @task_months.keys.sort.each do |month| %>
  <h2><%= month.strftime('%B') %></h2>
  <% for task in @task_months[month] %>
  <div class="task">
    <strong><%= task.name %></strong>
    due on <%= task.due_at.to_date.to_s(:long) %>
  </div>
  <% end %>
<% end %>

你可能感兴趣的:(ext,Rails)