class ApplicationUpload attr_accessor :filename attr_accessor :content_type attr_accessor :size attr_accessor :data def initialize(file) unless file.blank? begin @filename = file.original_filename.gsub(/[^\w!\#$%&()=^~|@`\[\]\{\};+,.-]/u, '') @content_type = file.content_type.gsub(/[^\w.+;=_\/-]/n, '') @size = file.size @data = file.read rescue end end end def to_a require 'csv' arrs = [] CSV.parse(@data){|line| row = [] line.each_with_index{|col,j| row << col } arrs << row } return arrs end def import(instance) upload_msga = [] upload_cols = instance.columns exclude_cols = ["id", "lock_version", "created_at", "updated_at"] self.to_a.each_with_index{|row,i| if i > 0 id = 0 object = nil row.each_with_index{|data,j| data = Kconv.toutf8(data.to_s) if j == 0 begin id = data.to_i object = instance.find(id) rescue id = 0 object = instance.new upload_cols.each{|col| if exclude_cols.index(col.name).blank? object[col.name] = "" object[col.name] = 0 if col.type.to_s == "integer" end } end else begin if exclude_cols.index(upload_cols[j].name).blank? begin object[upload_cols[j].name] = data rescue object[upload_cols[j].name] = "" end end rescue end if j == (upload_cols.size - 1) upload_msga << object.errors.full_messages.to_s if object.invalid? if object.save id = object.id begin object_name = object.name_with_id rescue object_name = sprintf(FORMAT_NAME_WITH_ID, object.id, object.name) end upload_msga << object_name + (id == 0 ? " create." : " update.") end end end } end } upload_msgs = upload_msga.join("/") return upload_msgs end def import_by_sql(table) msg = [] col = [] sql_header = "" sql = "" exd = ["id", "lock_version", "created_at", "updated_at"] self.to_a.each_with_index{|row,i| if i == 0 sql_header = "insert into #{table} (" row.each_with_index{|data,j| if exd.index(data).blank? col << data sql_header += data + "," end } sql_header = sql_header.slice(0, sql_header.size - 1) sql_header += ") values (" elsif i > 0 sql = sql_header row.each_with_index{|data,j| if exd.index(data[j]).blank? data = Kconv.toutf8(data.to_s) sql += "'" + data.gsub("'", " ") + "'," end } sql = sql.slice(0, sql.size - 1) sql += ")" begin ActiveRecord::Base.connection.execute(sql) rescue => e p e end end } return msg end end