用于main的未定义局部变量或方法`column':通过rake运行csv import时的对象

时间:2013-09-20 05:31:01

标签: ruby-on-rails ruby csv

我正在尝试学习Rails,我想学习的第一个练习之一就是将csv导入数据库自动化。所以我使用

创建了模型
rails g scaffold Domain  dns:string current_bid:integer join_by_pt:datetime bidders:integer seller:string tld:string length:integer words:string categories:string hyphnens:string numbers:string auction_type:string

接下来我创建了rake文件:

require 'csv'

desc "Import domains from csv file"
  task :import => [:environment] do

  file = "db/dl.txt"

  CSV.foreach(file, :headers => true) do |row|
  entry = Domain.find_or_create_by(:dns => column[1])
  entry.bid = column[2]
  entry.join_date = DateTime.parse(column[3])
  entry.bidders = column[4]
  entry.seller = column[5]
  entry.tld = column[6]
  entry.length = column[7]
  entry.words = column[8]
  entry.categories = column[9]
  entry.hyphens = column[10]
  entry.numbers = column[11]
  entry.auction_type = column[12]
  entry.save 
 end

end

但是当我尝试运行它时,我收到错误:

> rake aborted! undefined local variable or method `column' for
> main:Object /Users/user/drop/lib/tasks/import.rake:9:in `block (2
> levels) in <top (required)>'
> /Users/uer/drop/lib/tasks/import.rake:8:in `block in <top (required)>'

关于我做错了什么以及我的思路偏向错误方向的指示?

谢谢

1 个答案:

答案 0 :(得分:1)

尝试将您的所有column改为row

desc "Import domains from csv file"
 task :import => [:environment] do

 file = "db/dl.txt"

 CSV.foreach(file, :headers => true) do |row|
  entry = Domain.new
  entry.dns =  row[1] unless row[1].nil?  
  entry.bid = row[2] unless row[2].nil?
  entry.join_date = DateTime.parse(row[3]) unless row[3].nil?
  entry.bidders = row[4] unless row[4].nil?
  entry.seller = row[5] unless row[5].nil?
  entry.tld = row[6] unless row[6].nil?
  entry.length = row[7] unless row[7].nil?
  entry.words = row[8] unless row[8].nil?
  entry.categories = row[9] unless row[9].nil?
  entry.hyphens = row[10] unless row[10].nil?
  entry.numbers = row[11] unless row[11].nil?
  entry.auction_type = row[12] unless row[12].nil?
  entry.save 
 end
end