在Rails3中按日期格式化输出

时间:2012-01-17 03:04:19

标签: ruby-on-rails activerecord ruby-on-rails-3.1

我已关注this帖子,了解有关按日期对一组结果进行分组并添加计数的说明。

我视图中的输出如下所示:

 {Sun, 30 Oct 2011=>17, Wed, 02 Nov 2011=>19, Fri, 11 Nov 2011=>70, Sat, 12 Nov 2011=>44, Sun, 13 Nov 2011=>38, Sun, 20 Nov 2011=>4, Mon, 21 Nov 2011=>5, Sun, 27 Nov 2011=>80, Sun, 04 Dec 2011=>16, Sat, 31 Dec 2011=>48, Mon, 02 Jan 2012=>68, Tue, 03 Jan 2012=>1, Wed, 04 Jan 2012=>3, Sun, 08 Jan 2012=>9, Mon, 09 Jan 2012=>7, Wed, 11 Jan 2012=>1, Thu, 12 Jan 2012=>1}

我有这是我的控制器:

@radpostauth = Radpostauth.order(:authdate).group("DATE(authdate)").count

我不确定如何在表格中格式化此输出?任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

该查询将返回一个哈希,因此您需要做的就是遍历哈希并将其显示在表中。

以下是迭代它的快速示例:

$ hashish = Hash.new
$ hashish = {'Sun, 30 Oct 2011'=>17, 'Wed, 02 Nov 2011'=>19, 'Fri, 11 Nov 2011'=>70, 'Sat, 12 Nov 2011'=>44, 'Sun, 13 Nov 2011'=>38, 'Sun, 20 Nov 2011'=>4, 'Mon, 21 Nov 2011'=>5, 'Sun, 27 Nov 2011'=>80, 'Sun, 04 Dec 2011'=>16, 'Sat, 31 Dec 2011'=>48, 'Mon, 02 Jan 2012'=>68, 'Tue, 03 Jan 2012'=>1, 'Wed, 04 Jan 2012'=>3, 'Sun, 08 Jan 2012'=>9, 'Mon, 09 Jan 2012'=>7, 'Wed, 11 Jan 2012'=>1, 'Thu, 12 Jan 2012'=>1}
$ hashish.each {|k,v| puts "Key is #{k} and value is #{v}"}

> Key is Sun, 30 Oct 2011 and value is 17
> Key is Wed, 02 Nov 2011 and value is 19
> Key is Fri, 11 Nov 2011 and value is 70
> Key is Sat, 12 Nov 2011 and value is 44
> Key is Sun, 13 Nov 2011 and value is 38
> Key is Sun, 20 Nov 2011 and value is 4
> Key is Mon, 21 Nov 2011 and value is 5
> Key is Sun, 27 Nov 2011 and value is 80
> Key is Sun, 04 Dec 2011 and value is 16
> Key is Sat, 31 Dec 2011 and value is 48
> Key is Mon, 02 Jan 2012 and value is 68
> Key is Tue, 03 Jan 2012 and value is 1
> Key is Wed, 04 Jan 2012 and value is 3
> Key is Sun, 08 Jan 2012 and value is 9
> Key is Mon, 09 Jan 2012 and value is 7
> Key is Wed, 11 Jan 2012 and value is 1
> Key is Thu, 12 Jan 2012 and value is 1

这是一个在表格中显示的快速示例(我使用HAML代码,因为您没有指定ERB或HAML):

%table
  %tr
    - hashish.each do |k,v|
      %td #{k}
  %tr
    - hashish.each do |k,v|
      %td #{v}

或者

%table
  - hashish.each do |k,v|
    %tr
      %td #{k}
      %td #{v}