Skip to content

Instantly share code, notes, and snippets.

@akshaymohite
Created January 15, 2018 09:45
Show Gist options
  • Save akshaymohite/439ea6633a9403891060d3219f01ef8a to your computer and use it in GitHub Desktop.
Save akshaymohite/439ea6633a9403891060d3219f01ef8a to your computer and use it in GitHub Desktop.
Concern to help inserting records in Bulk in Rails
module BulkCreator
extend ActiveSupport::Concern
module ClassMethods
def bulk_create(columns, values, *args)
records_to_create(values, args).each_slice(500) do |records|
self.connection.execute bulk_insert_sql(columns, records)
end
end
def bulk_insert_sql(columns, records)
columns += [:created_at, :updated_at]
<<-SQL
INSERT INTO #{self.table_name} (#{columns.join(", ")})
VALUES #{records.join(', ')}
SQL
end
def records_to_create(values, *args)
values.map do |value|
"(#{value}, #{args.join(", ")}, '#{Time.current}', '#{Time.current}')"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment