2

I'm trying to import users avatar from a CSV and attach to the users with ActiveStorage.

I've created a rake task for this, but it's not working (and do not throws any error). In my CSV there are only 2 fields: email and avatar (avatar is the url to the file, that is on another server).

This is the task:

require 'csv'
namespace :import do
  desc "Import avatars to users from CSV"
  task avatars: :environment do
    filename = File.join Rails.root, "avatars.csv"

    CSV.foreach(filename, headers: true, col_sep: ";", header_converters: :symbol) do |row|
      User.find_by(email: row[:email]) do |u|
        u.avatar.attach(URI.parse(row[:avatar]).open)
      end
    end
  end
end

Any advice? Thanks for your help.

deikka
  • 23
  • 1
  • 3

1 Answers1

0

Have you tried to catch the any exception and print the problem in the console?

Something like that:

require 'csv'
namespace :import do
  desc "Import avatars to users from CSV"
  task avatars: :environment do
    begin
      filename = File.join Rails.root, "avatars.csv"

      CSV.foreach(filename, headers: true, col_sep: ";", header_converters: :symbol) do |row|
        User.find_by(email: row[:email]) do |u|
          u.avatar.attach(URI.parse(row[:avatar]).open)
        end
      end
    rescue StandardError => e
      logger = Logger.new(STDOUT)
      logger.error e.message
      logger.error e.backtrace.join("\n")
    end
  end
end

Also, are you sure you have users with that email?

mariotux
  • 36
  • 1
  • 3
  • Hi @mariotux. No errors with the code you provided, and yes, there are users with those emails. I'm starting to think that may be a devise validation? I forgot to mention that I use devise for authentication... Thanks for your answer. – deikka Sep 05 '19 at 20:52
  • I get this from the console but no error: 'irb(main):003:0> Rake::Task['import:avatars'].invoke User Load (15.1ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "email1@email.com"], ["LIMIT", 1]] User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "email2@email.com"], ["LIMIT", 1]] => [#]'. I've edited the path and emails, for privacy. – deikka Sep 06 '19 at 06:58