Ruby on rails 如果在Rails中的日期创建,则所有金额的总和相同
我正在尝试使用Rails数据库(pg)查询,但运气不太好 我的Ruby on rails 如果在Rails中的日期创建,则所有金额的总和相同,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我正在尝试使用Rails数据库(pg)查询,但运气不太好 我的Foo表有很多列,但我对在和金额中创建的感兴趣 Foo.all.where(客户端id:4)如下所示: [ [0] {:created_at => <date>, :amount => 20}, [1] {:created_at => <different date>, :amount => 5}, ... ] 无论如何,我的控制器: # As per first link
Foo
表有很多列,但我对在和金额中创建的感兴趣
Foo.all.where(客户端id:4)
如下所示:
[
[0] {:created_at => <date>, :amount => 20},
[1] {:created_at => <different date>, :amount => 5},
...
]
无论如何,我的控制器:
# 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中的JSconsole.log()
是否有一个等价物?会很方便。看起来f
通过调用as_json
存储为散列对象,但通过使用
操作符,您在每个用户\u foo
块中将其视为普通的旧Ruby对象
解决方案是使用哈希访问器操作符(例如f[:created\u at]
)。您也不需要字符串化和解析日期,因为它已经是一个DateTime
对象:
amount_date = f[:created_at].to_date # line 50
amount = f[:amount]
另外,Foo
是一个模型类,对吗?如果是这样的话,我建议使用pulk
来获取所需的属性,这将比调用as_json
更高效、更干净:
# As per first link above
def each_user_foo
f = Foo.where(client_id: 4).pluck(:created_at, :amount)
f.each do |bar|
yield(bar.first, bar.last)
end
end
foo_by_date = Hash.new(0)
each_user_foo do |created_at, amount|
# Parses date object. `to_date` converts a DateTime object to a date (daily resolution).
amount_date = created_at.to_date # line 50
foo_by_date[amount_date] += amount
end
您也可以删除此行:
foo_by_date[amount_date] ||= 0
因为您在foo\u by\u date=Hash.new(0)
变量赋值中使用了初始值设定项)
编辑
如果您正在使用Postgres,只需执行以下操作:
Foo.where(client_id: 4).group("date_trunc('day', created_at)").sum(:amount)
或者对于MySQL:
Foo.where(client_id: 4).group("DAY(created_at)").sum(:amount)
比您当前的方法简单得多
Rails中的console.log()
等效于Rails.logger.info()
,您还可以使用Rails.logger.warn()
和Rails.logger.error()
。实际上,任何输出到STDOUT
的功能,例如放置和打印
都将输出到您的控制台。啊,谢谢。我现在正在为Sun获取未定义的方法,2016年5月1日07:07:35 UTC+00:00:Time`当我使用Pulk
时。让我仔细检查所有内容。未定义的方法到\u日期为nil:NilClass
。我现在使用的是f=Hash[Foo.where(client\u id:4).pull(:created\u at,:amount)]
而不是我的第一个。对吗?关了pluck()
返回一个数组。使用f=Foo.all.where(client\u id:4).purch(:created\u at,:amount)
并使用yield Hash[bar]
生成块中数组的每个元素。查看我的更新答案。忘记删除,抱歉
Foo.where(client_id: 4).group("DAY(created_at)").sum(:amount)