Rails: 在交叉表中显示数据

Rails: showing data in a crosstab

我正在制作支出日记,因此我认为需要交叉表。该应用有一笔支出 table。 table 中的每条记录都是单一支出控股(除其他外)"Value"(作为整数),"Day"(作为日期)和 "Category_ID"(作为整数和外键) .

我想做的是显示一个 table 来显示用户每个月在每个类别上的花费。

因此我需要做两件事:

  1. 按月和类别对所有支出进行分组
  2. 在视图中显示

换句话说我想从:

收件人:

我怎样才能做到这一点?已经搜索了一段时间,但没有找到 suitable 解决方案。

此外,我想显示的不是 "Category_ID",而是类别的名称(来自类别 join table)。

更新: 到目前为止,我尝试了以下方法:

@expenditures = Expenditure.where(:user_id => current_user)
@grouped_exp = @expenditures.includes(:category).group("DATE_TRUNC('month', day)", :name).sum(:value)

现在给了我:

[[[2016-08-01 00:00:00 UTC, "housing | electricity"], -31.0], [[2016-09-01 00:00:00 UTC, "other | pharmacy & drugstore"], -9.5], [[2016-08-01 00:00:00 UTC, "financials | salary"], 2913.92], [[2016-10-01 00:00:00 UTC, "housing | internet"], -26.06], ... ]

所以我现在每个月都有每个类别的总和。但是,我不知道这是否是正确的方法,如果是,接下来的步骤是什么。

你可以试试这样:

@expenditures
  .joins(:category)
  .select('DATE_TRUNC('month', day) as day, category_id, sum(value) as total')
  .group('day, category_id, total')

您要创建的table不能这样操作。它似乎有与一年中的几个月相对应的动态列。这不能使用 ActiveRecord 来完成。您必须直接使用 SQL 并以编程方式生成始终选择每列特定日期范围的查询。除非你是某个 SQL 英雄,否则这可能不是一个好主意。

你需要的是更像这样的东西

Category.joins(:expenditures).
  where("expenditures.user_id = ?", current_user).
  group("categories.id, DATE_TRUNC('month', day)").
  select("categories.name, DATE_TRUNC('month', day) AS month, SUM(value) AS sum")

这会给你这样的记录

r = records.first
r.name => 'Some category'
r.month => '2016-10'
r.sum => 55