0

我正在尝试通过 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
4

1 回答 1

0

然后给出这些提示作为答案:

您共享的代码部分(假设其他部分的行为符合预期)似乎没问题,并且就像它正在做它应该做的但是因为您的图像没有创建......(删除了猜测部分)

编辑:在您的更新揭示了一些上下文之后,我的猜测是第一个版本(带ActiveRecord导入)不起作用,因为导入 gem 不会调用回调和/或可能跳过ActiveStorage触发文件上传所需的内容附件。

于 2020-01-07T19:31:33.690 回答