我正在使用mysql数据库。现在,我想从数据库中检索数据:值和时间,以绘制图形。我的数据库最多可存储4000个数据,而我需要绘制1000个数据。
我想到的第一种方法是:
points=Hash.new
Records.all.each do |record|
points[record.time.to_s]=record.value.to_s
end
然后削减前1000条记录。
但是这种方式将非常低效且耗时,这将导致我的网页加载时间过长。
我觉得必须有一种有效的方法来做到这一点?将前1000个数据库记录的属性转换为哈希?或转换为数组对也可以,只要数据对可以绘制即可。
谢谢!
data = Record.limit(1000) # Load no more than a 1000 entries
.pluck(:time, :value) # Pick the field values into sub-arrays
# it will also `SELECT` only these two
# At this point you have [[time1, value1], [time2, value2]]
# good already, but we can go further:
.to_h # Ruby 2.1+ only! I hope you're up-to-date!
# Now it is {time1 => value1, time2 => value2}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句