2012-11-21 76 views
1

我有一個問題。命令「耙分貝:種子」需要兩個小時,因爲myfriends.txt擁有超過3 Miliionen條目:RoR:'rake db:seed'需要兩個小時

File.open("lib/friends_name/myfriends.txt", "r").each_line do |row| 
    row = row.encode('utf-8', 'iso-8859-1').split(',') 
    Friend.create(name: row[0], first_name: row[1], age: row[2], sex: row[3], address: row[4]) 
end 

是否有一個更快的解決方案?我正在使用postgresql。

回答

1

使用PostgreSQL的COPY函數。這個工作在我寫它的時候,但它已經一段時間,因爲我用它...

Problems with postgresql COPY command with Rails on different server

重新粘貼代碼:

conn = ActiveRecord::Base.connection_pool.checkout 
raw = conn.raw_connection 
raw.exec("COPY tablename (col1, col2, col3) FROM STDIN") 
# open up your CSV file looping through line by line and getting the line into a format suitable for pg's COPY... 
rc.put_copy_data line 
# once all done... 
rc.put_copy_end 
while res = rc.get_result do; end # very important to do this after a copy 
ActiveRecord::Base.connection_pool.checkin(conn) 
+0

在這一點,文件「 lib/friends_name/myfriends.txt「必須指定?是正確的:raw.exec(「複製朋友(姓名,名字,年齡,性別,地址)從'lib/friends_name/myfriends.txt'」)rc.put_copy_data line.encode('utf-8','iso- 8859-1')。split(',') – AasimOnRails

+0

這取決於文件的位置。如果該文件在服務器上並且可以被PostgreSQL服務器讀取,那麼是的,你可以這樣做。或者你可以像你一樣繼續閱讀它,並把它變成一個'line'變量,你可以輸入到psql的COPY中。我完全不記得格式,但它在文檔中。鏈接:http://www.postgresql.org/docs/9.2/static/sql-copy.html –

+0

我很好奇這行代碼:「while res = rc.get_result do; end」及其對應的「very重要的「評論。你能否澄清該行的目的以及忽略它的後果?我是Ruby和PG的新手,我試圖避免複製和粘貼我不完全理解的內容。 – MothOnMars