0

我正在尝试将 CSV 文件导入到 Rails 项目中我的 SQLite3 数据库中的现有表中。

我已经尝试过这个解决方案的正确答案,但我得到了错误:

uninitialised constant Object::Points

这是我的主目录中的 data.csv 文件:

Item,2003,2004,2005,2006,2007
AA2,43,34,23,52,24
TT2,48,39,29,23,29

这是我保存在 app\models\points.rb 中的模型文件:

class Points < ActiveRecord::Base
  attr_accessible :Item, :2003, :2004, :2005, :2006, :2007
end

这是我保存在 db\migrate\20130709123346_create_points.rb 中的迁移文件:

class CreatePoints < ActiveRecord::Migration
  def change
    create_table :points do |t|
      t.varchar(255) :Item
      t.integer :"2003"
      t.integer :"2004"
      t.integer :"2005"
      t.integer :"2006"
      t.integer :"2007"  

      t.timestamps
    end
  end
end

以下是我根据上面链接的正确解决方案尝试过的:

  1. 创建名为 import.rake 的新文件并将其保存在 lib\tasks\import.rake 中:

    require 'csv'    
    
    csv_text = File.read('data.csv')
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
      Points.create!(row.to_hash)
    end
    
  2. 然后我bundle exec rake import.rake在命令行中运行。

运行后我得到错误:

uninitialised constant Object::Points

我一定遗漏了导致此错误的某些内容。我究竟做错了什么?

4

1 回答 1

1

您需要将您的内容定义import.rake为实际任务。此外,就您的代码而言,rake 对您的 Rails 环境一无所知,这就是它找不到Points. 例如

require 'csv'

namespace :import do
  task :points => :environment do
    csv_text = File.read('data.csv')
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
      Points.create!(row.to_hash)
    end
  end
end

然后从命令行

bundle exec rake import:points

对任务的=> :environment依赖是启动 Rails 环境的原因。

于 2013-07-15T14:15:31.307 回答