2011-05-04 54 views

回答

2

你可以使用Ruby的內置CSV庫來讀取數據到一個數組,然後你就可以做任何你需要用:

CSV.foreach("path/to/file.csv") do |row| 
    # use row here... 
    # For example, if you had users in a CSV file like "username,email" you could do: 
    User.create(:username => row[0], :email => row[1]) 
end 
+0

聽起來正是我想要的,但是當我嘗試在控制檯中運行它,我得到這樣的: – Augusto 2011-05-04 16:05:26

+0

NameError:未初始化不斷CSV \t from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.6/lib/active_support/dependencies.rb:443:in'load_missing_constant' \t from /Library/Ruby/Gems/1.8/gems/activesupport- 2.3.6/lib/active_support/dependencies.rb:80:在'const_missing_not_from_s3_library' \t from /Users/phishman/.gem/ruby/1.8/gems/aws-s3-0.6.2/lib/aws/s3/extensions .rb:206:'const_missing' \t from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.6/lib/active_support/dependencies.rb:92:in'const_missing' \t from(irb): 4 – Augusto 2011-05-04 16:05:45

+1

我發現我需要之前:「require'csv'」 – Augusto 2011-05-04 16:15:43

3

我有像這樣的東西成功:

require 'csv' 
CSV.foreach(Rails.root.to_s+"/db/calseed_test1.csv") do |row| 
Calevent.create(
:caldate => row[0], 
:caltime => row[1], 
:callocation => row[2], 
:caldescription => row[3] 
) 
end 
相關問題