RoR:'rake db:seed'需要两个小时

时间:2012-11-21 13:04:17

标签: database ruby-on-rails-3.2 rails-postgresql

我有问题。命令'rake db:seed'需要两个小时,因为myfriends.txt有超过3个Miliionen条目:

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 个答案:

答案 0 :(得分: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)