2015年9月3日 星期四

[RoR]使用activerecord-import寫入大量資料

Rails的ActiveRecord並不支援大批量的資料轉入,若採用原有的create method跟save method會造成每筆transaction都對DB做一次commit,使得performance明顯低落,因此使用activerecord-import來做大量資料轉入的工作。


安裝

  • 在Gemfile新增 gem 'activerecord-import'
  • 執行bundle install

使用


  • 先宣告一個Array
  • 透過Loop把一筆筆的資料用Model.new的方式存入Array中
  • 使用import function把Array的資料一次性寫入

#大批量資料轉入
  def bulk_import
    customer_list = []
    pos_member = Pos_member.all
    pos_member.each do |m|
        customer_list << Customer.new(:source_type => m.source_type,:orig_cust_id => m.orig_cust_id,:cust_no => m.cust_no,
                                      :name => m.name, :birth_year => m.birth_year, :birth_month => m.birth_month,
                                      :birth_day => m.birth_day, :phone => m.phone, :zip_code => m.zip_code,
                                      :country => m.country, :province => m.province, :county => m.county,
                                      :city => m.city, :address => m.address, :email => m.email,
                                      :id_no => m.id_no, :referral_cust_id => "", :merge_cust_id => "");        
    end
    Customer.import customer_list
  end

沒有留言: