ruby-on-rails - 嵌套 group_by 和在 Rails 上对 ruby​​ 进行排序

标签 ruby-on-rails nested-loops

型号

1 个平面发票表,其中包含 sales_invoice_date、you_ref 等字段

Controller

def raw
  @invoices = Invoice.find(:all, :order => 'sales_invoice_date, id')
  @invoice_days =  @invoices.group_by { |day| day.sales_invoice_date }
end

查看

<% @invoice_days.sort.each do |day, invoices| %>
  <h2><%= day.to_date.to_s(:long) %></h2>
  <% for invoice in invoices %>
  <div class="invoice_line">
    <strong><%= invoice.your_ref %></strong>
    Sales invoice date: <%= invoice.sales_invoice_date.to_date.to_s(:long) %>
  </div>
  <% end %>
<% end %>

这让我实现了目标一半。它打印以下内容:

September 9, 2012
    2222 Sales invoice date: September 9, 2012
    5555 Sales invoice date: September 9, 2012
    2222 Sales invoice date: September 9, 2012
October 1, 2012
    1111 Sales invoice date: October 1, 2012
    1111 Sales invoice date: October 1, 2012
    1111 Sales invoice date: October 1, 2012
November 11, 2012
    3333 Sales invoice date: November 11, 2012
December 12, 2012
    0000 Sales invoice date: December 12, 2012

我需要的是一种在日期循环中对唯一的“your_ref”值进行分组和再次排序的方法,它看起来像这样:

September 9, 2012
    2222
        2222 Sales invoice date: September 9, 2012
        2222 Sales invoice date: September 9, 2012
    5555
        5555 Sales invoice date: September 9, 2012

October 1, 2012
    1111
        1111 Sales invoice date: October 1, 2012
        1111 Sales invoice date: October 1, 2012
        1111 Sales invoice date: October 1, 2012
November 11, 2012
    3333
        3333 Sales invoice date: November 11, 2012
December 12, 2012
    0000
        0000 Sales invoice date: December 12, 2012

谢谢

最佳答案

而不是

  <% for invoice in invoices %>
    <div class="invoice_line">
      <strong><%= invoice.your_ref %></strong>
      Sales invoice date: <%= invoice.sales_invoice_date.to_date.to_s(:long) %>
    </div>
  <% end %>

尝试:

  <% invoices.group_by(&:your_ref).sort.each do |ref, ref_invoices| %>
    <div class="invoice_line">
      <strong><%= ref %></strong>
    </div>
    <% for invoice in ref_invoices %>
      <strong><%= invoice.your_ref %></strong>
      Sales invoice date: <%= invoice.sales_invoice_date.to_date.to_s(:long) %>
    <% end %>
  <% end %>

这还将按引用对发票进行分组。

关于ruby-on-rails - 嵌套 group_by 和在 Rails 上对 ruby​​ 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12989599/

相关文章:

ruby-on-rails - 是否可以使用载波仅重新创建特定版本?

mysql - COLLATE=utf8_unicode_ci 迁移后从 schema.rb 中删除

python - 嵌套 for 循环不会给出所有输出

c - 从文件中检索丢失的条目

ruby-on-rails - rails 3.0 : error with routes when overriding to_param in model

ruby-on-rails - rails 4 : How to test Controller Action

ruby-on-rails - rails formtastic - 以枚举为下拉列表的整数字段 - '0' 无效

java - Hi-Lo 猜谜游戏 - 限制用户输入的尝试次数和重玩逻辑

c# - 添加无限次嵌套代码

c - for循环不运行