[英]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.