【发布时间】:2016-05-01 20:28:08
【问题描述】:
我正在尝试使用 Rails 数据库 (pg) 查询 replicate this,但运气不佳。
我的Foo 表有很多列,但我对created_at 和amount 感兴趣。
Foo.all.where(client_id: 4) 看起来像这样:
[
[0] {:created_at => <date>, :amount => 20},
[1] {:created_at => <different date>, :amount => 5},
...
]
Stripe Charge Object 在 json 中,所以我想我可以:
f = Foo.all.where(client_id: 4).as_json # could I?
无论如何,我的控制器:
# As per first link above
def each_user_foo
starting_after = nil
loop do
f = Foo.all.where(client_id: 4).as_json
#f_hash = Hash[f.each_slice(2).to_a] # I was trying something here
break if f.none?
f.each do |bar|
yield bar
end
starting_after = bar.last.id
end
end
foo_by_date = Hash.new(0)
each_user_foo do |f|
# Parses date object. `to_date` converts a DateTime object to a date (daily resolution).
amount_date = DateTime.strptime(f.created_at.to_s, "%s").to_date # line 50
amount = f.amount
# Initialize the amount for this date to 0.
foo_by_date[amount_date] ||= 0
foo_by_date[amount_date] += amount
end
我在第 50 行的错误是:
哈希的未定义方法`created_at'
我猜一个对象仍在某个数组中。另外,Rails 中的 JS console.log() 是否有等价物?会很方便。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4