我该如何总结记录中的Rails 3? [英] How do I sum up records within Rails 3?

查看:157
本文介绍了我该如何总结记录中的Rails 3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ItemsSold模式,有杂志,书籍,视频,greeting_cards,为单日卖笔的总数。我如何优雅地返回与每周售出总计数组的每个项目数周的最后一个任意号码?

I have an ItemsSold model which has the total number of magazines, books, videos, greeting_cards, pens sold for a single day. How do I elegantly return an array with the weekly sold totals for each item for the last arbitrary number of weeks?

我有一个模型文件:

#items_sold.rb
class ItemsSold < ActiveRecord::Base
    attr_accessible :magazines, :books, :videos, :greeting_cards, :pens, :sold_date

end

我的表的定义如下:

My table is defined as follows:

t.integer :magazines
t.integer :books
t.integer :videos
t.integer :greeting_cards
t.integer :pens
t.datetime :sold_date

此外,是否有可能恢复每月总计去年呢?

Also, is it possible to return monthly totals for the last year, too?

推荐答案

见的的ActiveRecord ::#计算之

by_week = (1...10).inject({}) do |wh, weeks_ago|
  startat = weeks_ago.weeks.ago
  endat = (weeks_ago - 1).weeks.ago
  wh[weeks_ago] = [:magazines, :books, :videos, :greeting_cards, :pens].inject({}) do |sh, attr|
    sh[attr] = ItemsSold.where("sold_date > ? and sold_date <= ?", startat, endat).sum(attr.to_s)
    sh
  end
  wh
end

这将返回象散{1 =&GT; {:杂志=&GT; 5,:书=&GT; 33,...},2 =&GT; {{:杂志=&GT; 13日:书=&GT; 28,...}},...} ,其中每个关键是周数(1过去的这个星期,2两个星期前,等等)和值是另一个哈希用的款项。

That will return a hash like {1 => {:magazines => 5, :books => 33, ...}, 2 => {{:magazines => 13, :books => 28, ...}}, ...}, where each key is a week number (1 for this past week, 2 for two weeks ago, etc..) and the value is another hash with the sums.

这篇关于我该如何总结记录中的Rails 3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆