Created
May 26, 2012 11:14
-
-
Save jurgens/2793551 to your computer and use it in GitHub Desktop.
Speed up bulk insert operation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yay Ruby!!