我必须使用phonenumbers从文件中加载很多客户端
我的模特客户:名字 has_many:telnumbers
Telnumbers:number,:comment
所以我做了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"}}}
但我的代码不喜欢我。请帮我干一下。
答案 0 :(得分: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"}}}