How can I import a CSV file via a rake task?

后端 未结 5 609
梦如初夏
梦如初夏 2020-12-29 05:28

I know this question has been asked a lot on this forum but I\'m under a strict deadline and I need some help, so any advice is much appreciated. I\'m new to Ruby on Rails

5条回答
  •  [愿得一人]
    2020-12-29 06:16

    I've used this one in the past. It takes any type of model.

    rake csv_model_import[bunnies.csv,Bunny]

    Works like a charm.

    desc "Imports a CSV file into an ActiveRecord table"
    task :csv_model_import, :filename, :model, :needs => :environment do |task,args|
      lines = File.new(args[:filename]).readlines
      header = lines.shift.strip
      keys = header.split(',')
      lines.each do |line|
        params = {}
        values = line.strip.split(',')
        keys.each_with_index do |key,i|
          params[key] = values[i]
        end
        Module.const_get(args[:model]).create(params)
      end
    end

提交回复
热议问题