我必须从文件中加载很多带有电话号码的客户
我的模型客户:名称 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"}}}
但我的代码不像我。请帮我把它擦干。