我有一个名为 PageDensity
的模型,它有大约 500 万行。
当我创建项目PageDensity
表时,它以密度
的形式存储了5位小数精度的 float 。
现在要求更改为将其四舍五入到小数点后两位。
我只是编写了一个任务来舍入所有密度
,但它使系统变得如此沉重而卡住。即使我不能使用查询
,因为我的舍入有点变化,例如0.57500
将四舍五入为0.57
和0.57600
将四舍五入为 0.58
。
到目前为止我尝试过的很简单:
task round_densities: :environment do
application_object = ApplicationController.new
time = Benchmark.realtime do
ActiveRecord::Base.transaction do
PageDensity.all.each {|p| p.update_attributes(density: application_object.round_number(p.density))}
end
end
puts '***************************************'
puts "Total Time Consumed #{time} seconds"
puts '***************************************'
end
我也尝试进行舍入查询但失败了:
select round(0.00500, 2)
#this returns 0.01 as this should return 0.00
我正在使用 postgres
任何想法来使其 psql 查询
或使用 rails
吗?
最佳答案
听起来您的舍入要求仅比正常舍入少 0.001。
在这种情况下,我认为您可以运行 sql 更新:
update page_densities set density = round(density - 0.001, 2)
这将像这样舍入:
0.011 => round(0.010, 2) => 0.01
0.015 => round(0.014, 2) => 0.01
0.016 => round(0.015, 2) => 0.02
0.02 => round(0.019, 2) => 0.02
关于ruby-on-rails - 更新rake任务中的海量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30184944/