Search code examples
rubyruby-on-rails-3rake

Error message when running Rake command in Rails app


I'm trying to create posts in my Rails app by pulling data from a CSV file.

When I try to run a Rake command, I get the error message below. What's wrong with this code?

SEED.RAKE FILE

require 'csv'

namespace :csv do

  desc "Import CSV Data for Michelin Star Restaurants"
  task :post => :environment do

    csv_file_path = 'db/data.csv'

    CSV.foreach(csv_file_path) do |row|
        Post.create({
          :name => row[1],
          :address => row[2],
          :city => row[3],
          :michelin_status => row[4],
          :website => row[5],
          :phone => row[6],
          :longitude => row[7],
          :latitude => row[8],
          :inthenews => row[9],
          :google_reviews => row[10],
        })
      end
    end
  end

ERROR MESSAGE FROM CONSOLE

Faisals-Air:dinner fkhalid2008$ rake csv:post
rake aborted!
ArgumentError: invalid byte sequence in UTF-8
/Users/fkhalid2008/dinner/lib/tasks/seed.rake:11:in `block (2 levels) in <top (required)>'
/Users/fkhalid2008/.rvm/gems/ruby-2.2.0/bin/ruby_executable_hooks:15:in `eval'
/Users/fkhalid2008/.rvm/gems/ruby-2.2.0/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => csv:post
(See full trace by running task with --trace)

DB MIGRATE FILE

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :name
      t.string :inthenews
      t.string :michelin_status
      t.string :google_reviews
      t.string :address
      t.string :city
      t.string :website
      t.integer :phone
      t.integer :longitude
      t.integer :latitude

      t.timestamps null: false
    end
  end
end

CSV FILE SCREENSHOT csv file screenshot


Solution

  • This is because somewhere in your file there are some invalid bytes.

    To avoid this issue, you can use scrub method like this:

    CSV.foreach(csv_file_path) do |row|
      Post.create({
                      :name => row[1].scrub,
                      :address => row[2].scrub,
                      :city => row[3].scrub,
                      :michelin_status => row[4].scrub,
                      :website => row[5].scrub,
                      :phone => row[6].scrub,
                      :longitude => row[7].scrub,
                      :latitude => row[8].scrub,
                      :inthenews => row[9].scrub,
                      :google_reviews => row[10].scrub,
                  })
    end
    

    Update

    Try to specify the encoding type when you read the CSV file like this:

    CSV.foreach(csv_file_path, "r:ISO-8859-1") do |row|
     . . . 
     . . . 
    end