1

我正在尝试学习 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)>'

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

谢谢

4

1 回答 1

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
于 2013-09-20T05:39:43.277 回答