0

我必须从文件中加载很多带有电话号码的客户

我的模型客户:名称 has_many :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"}}}

但我的代码不像我。请帮我把它擦干。

4

1 回答 1

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"}}}
于 2013-03-19T09:56:47.240 回答