我正在創建一個原始的SQL upsert,並且我有一個相當大的ActiveRecord關係數組,我需要將其轉換爲散列。我需要使用我選擇的其中一個參數來鎖定哈希值,以便快速獲得該值。如何將一個ActiveRecord關係數組轉換爲一個散列的參數?
I found this response using as_json我幾乎可以得到我需要的東西,但它不是那樣。
profiles = Profile.all.select(:id, :foo) #returns an array of ActiveRecord Relations
profiles = profiles.as_json
息率
{:id => 123, :foo => "bar"}
{:id => 456, :foo => "baz"}
但我想是
{123 => "bar", 456 => "baz"}
我意識到,我可以as_json的結果映射到一個新的哈希,但我必須運行此在幾百萬條記錄上相當頻繁地發生。這也是一個更大的rake任務的一小部分,我想繼續循環所有的記錄到最小。
我之所以這樣做是爲了手動完成這一切,而不是讓ActiveRecord處理它,原因是它最初需要24小時以上才能運行任務,甚至使用activerecord-import也只能加速到12小時。 I chose to go with using raw sql based off the benchmarks made in this blogpost
什麼是你的軌道版本? – Santhosh
我正在使用Rails 4.2.4 – wslater