我用于表插入/更新的方法,并且在ruby中保存太慢了。我怎样才能加快速度呢?

时间:2013-03-13 15:18:11

标签: ruby-on-rails ruby activerecord

Ruby noob alert:花了8小时在ruby中插入300,000条记录。这是非常缓慢的。如何改进以下代码?下面,对于连接对象的每次获取行,我正在进行活动记录保存。我已经得出结论,这是导致大部分缓慢的原因。如何更改代码以使插入更快?

class SiteSection < ActiveRecord::Base

  SiteSection.establish_connection(
        :adapter  => 'postgresql',
        :host     => 'hoster-of-hosts.com',
        :database => 'super-inven',
        :username => 'user',
        :password => 'pass'
                      )
  self.table_name = 'master.target_tbl'  # << insert into this table
end

conn.query("select * from source_tbl") do |row|
  siteData = SiteSection.find_or_initialize_by_head_date_and_center_id_and_site_url(row[:date_c], row[:com_id], row[:site_link])

  siteData[:head_date]      = row[:date_c]
  siteData[:center_id]     = row[:com_id]
  siteData[:site_url]          = row[:site_link]
  siteData[:people_cnt]      = row[:persons]
  siteData[:ips]     = row[:ip_adds]

  siteData.save  # For every record from source_tbl query, save it in master.target_tbl.
i = i+1
puts "finished: #{i}" if i % 10000 == 0
end
conn.close

谢谢!

0 个答案:

没有答案