activerecord-import
activerecord-import copied to clipboard
Is it possible to import nested attributes containing remote urls?
I'm trying to create records from a csv file. Each row of the CSV file will be a new record.
def import
ads = []
CSV.foreach(file.path, headers: true, encoding: encoding) do |row|
ad = Ad.new
ad.title = row['title'] || ''
ad.description = row['description'] || ''
# Ad has_one: variant
ad.variant_attributes = initialize_ad_variant(row).attributes
ads << ad
end
Ad.import(ads, recursive: true) # I'm using postgres
end
def initialize_ad_variant(row)
variant = Variant.new
# inside CSV I have a column called 'custom_image_url', which contains an image url from where we need to save the image.
# 'custom_image' is the field name in variant table. I'm using carrierwave.
variant.remote_custom_image_url = row['custom_image_url']
variant.custom_text = row['custom_text']
return variant
end
The above code inserts Ad
s with associated variant
s. But seems like the images are not uploaded inside the variant table. Only the custom_text
is inserted.
Is there any way to bulk upload nested attributes like this; where the images will be uploaded from remote url?
I don't think so at this time. Are you using ActiveStorage? This might be a duplicate of issue #661.
I don't think so at this time. Are you using ActiveStorage? This might be a duplicate of issue #661.
Got it. No, I'm not using ActiveStorage.
Without knowing more of the internals of how the remote images are loading it's hard to give any suggestions. I would say try to find out if there is some type of call you make on each variant to manually load the image before importing.
Hi all I found a solution for this on StackOverflow https://stackoverflow.com/questions/69555467/bulk-creating-objects-with-nested-attributes-in-ruby/69555693#69555693