[英]Nested hash and rake task
我必須從文件中加載許多具有電話號碼的客戶端
我的模型客戶:名稱has_many:電話號碼
電話號碼:號碼,:注釋
所以我已經完成了耙任務
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"}}}
但是我的代碼不喜歡我。 請幫助我晾干。
嘗試這個
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"}}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.