Search code examples
mysqlruby-on-railsunicodeutf-8smartercsv

no implicit conversion of String into Hash (smarter_csv gem, uploading a file with an imput)


I'm trying to save the info of a csv that have unicode characters into mysql on a Rails app,

The code error says:

TypeError in ImporterController#upload

no implicit conversion of String into Hash

and the issue comes int this line

@csv = SmarterCSV.process(params[:csv].tempfile, "r:bom|utf-8")

Edit Here the log

Started POST "/importer/upload" for 127.0.0.1 at 2018-02-14 17:46:31 +0100
Processing by ImporterController#upload as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"rnz9HzM4aKALO2By3YtSbADmdAEhW4C+iv+9XAB3JArI/B8DAYkGdrJDULCA20p+Hx2APP4yErP9YSycsGfxdA==", "csv"=>#<ActionDispatch::Http::UploadedFile:0x007fd80801c1f0 @tempfile=#<Tempfile:/tmp/RackMultipart20180214-26318-zurnez.csv>, @original_filename="got_characters.csv", @content_type="text/csv", @headers="Content-Disposition: form-data; name=\"csv\"; filename=\"got_characters.csv\"\r\nContent-Type: text/csv\r\n">, "commit"=>"Upload"}
Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)



TypeError (no implicit conversion of String into Hash):

app/controllers/concerns/character_mock.rb:46:in `import_create'
app/controllers/importer_controller.rb:6:in `upload'
  Rendering /home/marcos/.rvm/gems/ruby-2.4.0@hbo/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout

Solution

  • Solved!

    Finally what it required is to Alter Tables on MySQL for use utf8mb4 rather than just utf8, then:

    File.open(params[:csv].tempfile, "r:bom|utf-8") do |csv|
     chars = SmarterCSV.process(csv);
      chars.each do |char|
       #Then this will work
       Register.create(name: char[:name])
      end
     end
    end
    

    Also you can try Register.create(name: char[:name].force_encoding("UTF-8")

    Seems that a bug on MySQL cause that kind of issues.