Rails:上传csv文件以将其作为哈希处理

时间:2012-02-03 11:32:57

标签: ruby-on-rails csv hash

我有这个型号:

class Survey < ActiveRecord::Base
  attr_accessor :csvFile_file_name
  has_attached_file :csvFile, :path => ":rails_root/public/:class/:attachment/:id/:style_:basename.:extension"
  serialize :content, Hash

  #after_save :do_cvs_process

  def do_csv_process
    product = {}
    FasterCSV.foreach(self.csvFile.path, :headers => true, :col_sep => ",") do |row|    
       row.to_hash.each do |key, value| 
         product[key.underscore.to_sym] = value
       end
     end
     self.update_column(:content, {:first => product})
  end
end

我有几个问题:

  1. 由于标准的浏览器安全性,我必须上传文件并在使用csv处理它之前保存它以将其作为哈希值分配给我的:content属性...这就是为什么我使用update_column来避免回调。有一种聪明的方法吗?
  2. 不起作用!当回到视图<%= @survey.content %> rails告诉我它在预期哈希时找到了一个数组。

2 个答案:

答案 0 :(得分:0)

def self.import_csv_file(iFileName)
  c = CSV.open iFileName
  header= c.first.map{ |i| i.to_s.strip.downcase; }        
  c.each { |row|  import_hash( Hash[*header.zip(row).flatten] ); }
  c.close    
end 

我的产品类有一个import_hash方法,用于查找小写/空格标题,并将它们与产品中的字段相匹配。

product.name = hash['productname'] || hash['name']   #for example.

答案 1 :(得分:-2)

使用faster_csv gem。以下是一些快速链接:

[消息来源] https://github.com/JEG2/faster_csv

[DOCS] http://fastercsv.rubyforge.org/

[的cheatsheet] http://cheat.errtheblog.com/s/faster_csv/

请在粘贴问题之前在GitHub上做一些R&amp; D,这些问题已经存在。