activerecord-import icon indicating copy to clipboard operation
activerecord-import copied to clipboard

Is it possible to import nested attributes containing remote urls?

Open imtiaz-emu opened this issue 4 years ago • 4 comments

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 Ads with associated variants. 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?

imtiaz-emu avatar Jul 22 '20 05:07 imtiaz-emu

I don't think so at this time. Are you using ActiveStorage? This might be a duplicate of issue #661.

jkowens avatar Jul 24 '20 03:07 jkowens

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.

imtiaz-emu avatar Jul 24 '20 04:07 imtiaz-emu

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.

jkowens avatar Jul 24 '20 04:07 jkowens

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

BrandonTeixeiraStream avatar Oct 13 '21 12:10 BrandonTeixeiraStream