I am trying to import list of products via CSV, there is an image column with remote url. I am using activerecord import gem, when I use the setup below I don't get any errors or logs but images are not being created.
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
am I missing something? Or is there a better way to handle this.
I was able to import image with regular csv parse. Still not sure, why activerecord import didn't work. I think I will ask this in the gem's 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
Giving these prompts as an answer then:
The part of the code you shared (assuming other parts behave as expected) seems ok and like it is doing what it should but since your images are not created ... (removed guesses part)
Edit: after your update revealing some context, my guess is that the first version (with
ActiveRecord
import) didn't work as the import gem doesn't invoke callbacks and/or probably skips something that is required forActiveStorage
to trigger the upload of the file attachment.