要求' csv'
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
enrollment_hash = row.to_hash # exclude the price field
enrollment = Enrollment.where(id: enrollment_hash["id"])
if enrollment.count == 1
enrollment.first.update_attributes(enrollment_hash)
else
Enrollment.create!(enrollment_hash)
end
end
end
答案 0 :(得分:0)
实际上你的代码似乎有效。
我刚刚做了一些改进,以减少ActiveRecord查询的数量。
class Enrollment < ActiveRecord::Base
require 'csv'
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
enrollment_hash = row.to_hash # exclude the price field
enrollment = self.where(id: enrollment_hash["id"])
if enrollment.present?
enrollment.first.update_attributes(enrollment_hash)
else
self.create!(enrollment_hash)
end # end if !product.nil?
end # end CSV.foreach
end # e
end