ruby-on-rails-6 - 无法使用 ActiveStorage 在循环中创建或更新记录
问题描述
红宝石 2.6.3 轨道 6.0.3
我不知道为什么,当我尝试在循环中创建或更新记录,添加一个或多个附件时,只能更新一两个记录。我还仅使用一个附件测试了此行为,并且仅用于创建。但是行为是一样的。在下面的代码中,我正在尝试使用活动存储在 aws 上重新加载附件。但只有 1 条记录被更新。
namespace :uploads do
task migrate_to_active_storage: :environment do
Upload.where.not(csv_file_name: nil).find_each do |upload|
%w[csv log].map do |attachment_type|
attach_url = [
'https://',
ENV['AWS_BUCKET'],
".s3-#{ENV['AWS_REGION']}.amazonaws.com/",
upload.business.normalized_name,
'/upload/',
upload.id.to_s,
"/#{attachment_type}/",
upload.csv_file_name
].join
upload.send(attachment_type).attach(
io: open(attach_url),
filename: upload["#{attachment_type}_file_name"],
content_type: upload["#{attachment_type}_content_type"]
)
end
end
ap 'DONe WITH SUCCESS' # never appears
end
end
我已经设法解决了这个问题,使用 threds。但我不知道为什么它在上面的代码中不起作用。此解决方案工作正常。
namespace :uploads do
task migrate_to_active_storage: :environment do
uploads = Thread.new { Upload.ids }.value
uploads.each do |id|
Thread.new do
sleep 2
upload = Upload.find id
upload.update csv: get_attachment(upload, 'csv'),
log: get_attachment(upload, 'log')
end.join
end
end
end
def get_attachment(upload, attachment_type)
attachment_url = [
'https://',
ENV['AWS_BUCKET'],
".s3-#{ENV['AWS_REGION']}.amazonaws.com/",
upload.business.normalized_name,
'/upload/',
upload.id.to_s,
"/#{attachment_type}/",
upload["#{attachment_type}_file_name"]
].join
{
io: open(attachment_url),
filename: "#{upload.id}_#{upload["#{attachment_type}_file_name"]}",
content_type: upload["#{attachment_type}_content_type"]
}
end
什么是真正的神秘主义者。例如,当我尝试调用不同的模型时,例如 User。即使它什么都不做,上面的代码也不起作用。只有 1 条记录将被更新。