[英]How to store database records into hash ruby on rails
我正在使用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}
您可以使用limit :
points = Record.limit(1000).map { |r| { r.time => r.value } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.