如何在rails中从数据库更新和删除csv文件中的记录

时间:2016-09-21 04:50:56

标签: ruby-on-rails csv

要求' 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

1 个答案:

答案 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