在Rails应用程序中运行Rake命令时出现错误消息

时间:2015-09-24 01:29:53

标签: ruby ruby-on-rails-3 rake

我试图通过从CSV文件中提取数据来在我的Rails应用中创建帖子。

当我尝试运行Rake命令时,我收到以下错误消息。这段代码有什么问题?

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

来自控制台的错误消息

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文件屏幕 csv file screenshot

2 个答案:

答案 0 :(得分:1)

这是因为文件中某处存在一些无效字节。

要避免此问题,您可以使用scrub这样的方法:

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

更新

尝试在您阅读CSV文件时指定encoding类型:

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

答案 1 :(得分:0)

您只需使用nkf将原始csv文件转换为utf8。

$ nkf -w --overwrite db/data.csv