SQL 批量插入的方法:
INSERT INTO events (event_type, user_id) VALUES("test", 2),("test", 5),("test", 8) ...;
ref: ,
关于第三种方式,有 Gem 帮助我们简单来实现:
# Gemfilegem 'bulk_insert'
然后我们就可以用了:
Event.bulk_insert(set_size: 100) do |worker| receiver_ids.each do |user_id| worker.add({ user_id: user_id, event_type: 'test' }) end end
然大码实现多条插入:
class ActiveRecord::Base
def self.import!(record_list)
raise ArgumentError "record_list not an Array of Hashes" unless record_list.is_a?(Array) && record_list.all? { |rec| rec.is_a? Hash }
key_list, value_list = convert_record_list(record_list)
sql = "INSERT INTO #{ self.table_name} (#{ key_list.join(", ")}) VALUES #{ value_list.map { |rec| "(#{ rec.join(", ")})" }.join(" ,")}"
self.connection.insert_sql(sql)
end
def self.convert_record_list(record_list)
key_list = record_list.map(&:keys).flatten.uniq.sort
value_list = record_list.map do |rec|
list = [] key_list.each { |key| list << ActiveRecord::Base.connection.quote(rec[key]) }
list
end
return [key_list, value_list]
end
end