Created
January 15, 2018 09:45
-
-
Save akshaymohite/439ea6633a9403891060d3219f01ef8a to your computer and use it in GitHub Desktop.
Concern to help inserting records in Bulk in Rails
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
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