如何将数据库记录存储到rails

时间:2015-06-17 08:33:33

标签: mysql ruby-on-rails hash

我正在使用mysql数据库。 现在我想从我的数据库中检索数据:值和时间,用于绘制图形。 我的数据库存储了多达4000个数据,我需要绘制1000个数据。

我想到的第一种方法是:

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

然后削减前1000条记录。

但这种方式效率非常低且耗时,这会导致我的网络加载时间过长。

我觉得必须有一种有效的方法吗? 将前1000个数据库记录的属性转换为哈希? 或转换为数组对也可以,只要数据对可以绘图。

谢谢!

2 个答案:

答案 0 :(得分:4)

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}

答案 1 :(得分:2)

您可以使用limit

points = Record.limit(1000).map { |r| { r.time => r.value } }