2015-06-17 81 views
0

我正在使用mysql數據庫。 現在我想從我的數據庫檢索數據:值和時間,繪圖圖。 我的db存儲多達4000個數據,我需要繪製1000個數據。如何將數據庫記錄存儲到軌道上的散列紅寶石

,我想起第一種方法是:

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

然後切第1000條記錄。

但是這種方式會非常低效且耗時,這會導致我的網絡負載過長。

我覺得必須有一個有效的方式來做到這一點? 將前1000個數據庫記錄的屬性轉換爲散列? 或轉換爲陣列對也可以,只要數據對可以繪圖。

謝謝!

+0

嘗試使用'Record.find_each做|記錄|'和使用'limit'獲取1000多項紀錄 – Sontya

+0

你的意思是'點[user.time .to_s] = record.value.to_s'?並且'user.time.to_s'對每個'record'都應該是一樣的? – thebenedict

+0

對不起的拼寫錯誤應該是:points [record.time.to_s] = record.value.to_s – Orz

回答

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

非常好。注意'.to_h'不在Ruby 2.0中。 – thebenedict

+1

@thebenedict好點。測試它,並添加它。 –

2

您可以使用limit

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