简体   繁体   English

如何将数据库记录存储到Rails的哈希红宝石中

[英]How to store database records into hash ruby on rails

I'm using mysql database. 我正在使用mysql数据库。 Now I want to retrieve data from my database: value and time, for plotting graph. 现在,我想从数据库中检索数据:值和时间,以绘制图形。 my db store up to 4000 data,and I need plot 1000 of them. 我的数据库最多可存储4000个数据,而我需要绘制1000个数据。

First method come to my mind is: 我想到的第一种方法是:

points=Hash.new
Records.all.each do |record|
  points[record.time.to_s]=record.value.to_s
end

then cut the first 1000 records. 然后削减前1000条记录。

But this way will be very inefficient and time consuming,It will cause my web load long. 但是这种方式将非常低效且耗时,这将导致我的网页加载时间过长。

I feel there must be a efficient way of doing this? 我觉得必须有一种有效的方法吗? convert first 1000 database records's attributes into hash? 将前1000个数据库记录的属性转换为哈希? or convert to array pairs also ok for me,as long as data pair can plot. 或将其转换为数组对也可以,只要数据对可以绘制即可。

thanks! 谢谢!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM