我正在尝试通过 CSV 导入产品列表,有一个带有远程 url 的图像列。我正在使用 activerecord 导入 gem,当我使用下面的设置时,我没有收到任何错误或日志,但没有创建图像。
require 'open-uri'
file = open(row['image'])
product = Product.new(
name: row['name'],
sku: row['sku'],
brand_id: row['brand']
)
product.image.attach(io: file, filename: row['sku']+ '.jpg', content_type: 'image/jpg')
products << product
end
importing = Product.import products, recursive: true
我错过了什么吗?或者有没有更好的方法来处理这个问题。
我能够使用常规 csv 解析导入图像。仍然不确定,为什么 activerecord 导入不起作用。我想我会在 gem 的 github 上问这个。
csv_text = resp.body
csv = CSV.parse(csv_text, :headers => true, :encoding => 'utf-8')
csv.each do |row|
file = open(row['image'])
t = Product.new
t.name = row['name']
t.image.attach(io: file, filename: row['name']+ '.jpg', content_type: 'image/jpg')
t.save
puts "#{t.name} saved"
end