2013-03-19 88 views
0

我必須從文件很多客戶的加載與PHONENUMBERS嵌套哈希和rake任務

我的模型客戶:命名 的has_many:telnumbers

Telnumbers:號碼,:發表評論

所以我有做rake任務

desc "Loads file clients from excell" 
task :loadclientsfromfile do 
require 'csv' 
require 'active_support/core_ext/hash' 

csv_text = File.read('c:\ddd1.csv') 
csv = CSV.parse(csv_text, :headers => true) 
csv.each do |row| 
    telnumbers = row.to_hash.slice("number","comment") 
    raw = row.to_hash.slice("name") 
    raw = raw.to_hash.symbolize_keys 
    telnumbers = telnumbers.to_hash.symbolize_keys 
    telnumber1 = {} 
    telnumber1["0"] = telnumbers 
    raw[:telnumbers_attributes] = telnumber1 
    Client.create!(raw) 
end 

我的CSV文件:

name,number,comment 
Second CLient,2343262,home 

我想要得到的哈希{:name=>"Second Client", :telnumbers_attributes=>{"0"=>{:number=>"2343262",:comment=>"home"}}}

但我的代碼不喜歡我。請幫助我幹掉它。

回答

1

試試這個

desc "Loads file clients from excell" 
task :load_clients_from_file do 
    file_path = 'c:\ddd1.csv' 
    lines = IO.readlines(file_path, :encoding => 'ISO-8859-1') 
    header = lines.shift.strip 
    keys = header.split(/,/) 
    lines.each do |line| 
    values = line.strip.split(/,/) 
    tel_hash = { "0" => {keys[1].to_sym => values[1], keys[2].to_sym => values[2]}} 
    raw = {keys[0].to_sym => values[0], :telnumbers_attributes => tel_hash} 
    Client.create!(raw) 
    end 
end 

這裏放出來的哈希看起來像下面

{:name=>"Second CLient", :telnumbers_attributes=>{"0"=>{:number=>"2343262", :comment=>"home"}}} 
+0

謝謝,這是有趣的方式。我的代碼也可以工作,但是我想讓它更簡單......通過方式,我可以將它記錄下來。 – Dmitry 2013-03-19 11:16:03