参考https://ruby-china.org/topics/17163
使用评论内首条的方法之一: 结合使用事务和直连sql的方式:
task move_data: :environment do
M.where.not(is_deleted: false).find_in_batches do |group|
# 一千条sql 一个COMMIT 节省commit的时间
ActiveRecord::Base.transaction do
group.each do |m|
g_id = Gmodel.find_by(m_id: m.id).id
# 使用sql语句插入
FModel.connection.execute "INSERT INTO fmodels \
(user_id, name, g_id, created_at, updated_at) \
VALUES \
(#{m.user_id}, 'ifree321', #{g_id}, '#{Time.now.utc.to_s[0,19]}', '#{Time.now.utc.to_s[0,19]}')"
end
end
end
end
附图可见,多条插入语句一个COMMIT
2019-09-26 at 11.43 AM.png
以上图为 本地开发环境测试。
网友评论