2011-06-24 76 views
1

閱讀this question後,我有這樣的耙子任務:Rails 3中,ActiveRecord的進口寶石,CSV

desc "Import sales" 
task :import_sales => :environment do 
    sales = File.open(Rails.root.join("public", "system", "xmls", "3", "original", "first.csv"),"r").map do |line| 
    isbn, date, quantity, value, channel = line.split("\,") 
    Importsale.new(:isbn => isbn, :date => date, :quantity => quantity, :value => value, :channel => channel) 
    end 
    Importsale.import sales 
end 

和一些像這樣的CSV數據:

9780953893201,30/5/10,4,25.6,UK Home 
9780953893201,25/6/10,3,19.2,UK Home 
9780953893201,30/7/10,6,95.94,UK Home 
9780953893201,27/8/10,1,15.99,Export 
9780953893201,27/8/10,13,207.87,UK Home 
9780953893201,27/8/10,1,6.4,UK Home 
9780953893201,24/9/10,14,223.86,UK Home 
9780953893201,24/9/10,5,32,UK Home 

但rake任務未分裂CSV文件 - 我收到一個記錄導入,最後一個頻道包含。

UK Home 
9780953893201 

是使用map停止csv解析爲行嗎?如果我使用each或each_line,那麼會出現「無效參數」錯誤。 。

+0

也許你想File.readlines(...)地圖做|線| ? –

+0

你做到了!謝謝。如果你喜歡,將它作爲答案扣除,我會打勾。 – snowangel

回答

2

因爲沒有人寫的答案...

File.readlines(...).map do |line| 
    ... 
end