Skip to content

Instantly share code, notes, and snippets.

@jurgens
Created May 26, 2012 11:14
Show Gist options
  • Save jurgens/2793551 to your computer and use it in GitHub Desktop.
Save jurgens/2793551 to your computer and use it in GitHub Desktop.
Speed up bulk insert operation
require 'activerecord-import'
class Product < ActiveRecord::Base
has_many :product_keywords, dependent: :delete_all
def update_product_keywords
self.product_keywords.delete_all
records = []
title_keywords.each do |keyword|
records << product_keywords.new(brand_id: brand_id, category_id: category_id, value: keyword)
end
ProductKeyword.import records
end
end
# second example runs 6 times faster
Product.where("updated_at > ?", 1.hour.ago).each do |product|
product.update_product_keywords
end
ActiveRecord::Base.transaction do
Product.where("updated_at > ?", 1.hour.ago).each do |product|
product.update_product_keywords
end
end
@loveybot
Copy link

Yay Ruby!!

@alg
Copy link

alg commented May 30, 2012

You are scaring me with these finds.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment