试图将postgres数据映射到我想要的格式

时间:2015-11-17 09:17:51

标签: ruby-on-rails postgresql

我有这些数据:

Model Account

# created_at | sales | profit 

[#<Account:0x007fcf3657dd90
  id: 1,
  balance: 500,
  profit: nil,
  user_id: 1,
  created_at: Sun, 15 Nov 2015 02:27:43 UTC +00:00,
  updated_at: Sun, 15 Nov 2015 02:27:43 UTC +00:00>,
 #<Account:0x007fcf3657dbb0
  id: 2,
  balance: 600,
  profit: 100,
  user_id: 1,
  created_at: Sun, 14 Nov 2015 15:05:07 UTC +00:00,
  updated_at: Sun, 15 Nov 2015 15:05:07 UTC +00:00>,
 #<Account:0x007fcf3657d9d0
  id: 3,
  balance: 1000,
  profit: 200,
  user_id: 1,
  created_at: Sun, 14 Nov 2015 15:07:04 UTC +00:00,
  updated_at: Sun, 15 Nov 2015 15:07:04 UTC +00:00>]

欲望格式:

[{ period: 15 Nov 2015,
   balance: 600,
   profit: 100
  }, 
 { period: '14 Nov 2015',
   balance: 1000,
   profit: 200
 }]

我试过这样的事情:

def total_group_by_week
 total_profit = Account.group("DATE_TRUNC('day', created_at)").sum(:profit)
 chart = total_profit.map do |k, v|
  {period: k, balance: ?, profit: v}
end
chart
end

我的问题是:

  1. 我能够获得总利润和日期。但我不知道如何在当天获得期末余额?

  2. 例如,我想将每周数据转换为该哈希格式,我该如何限制周期&#39;哈希值仅为过去7天?

0 个答案:

没有答案
相关问题