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

后端 未结 5 610
梦如初夏
梦如初夏 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 05:53

    Here is an example CSV that I imported using rake db:seed. I wrote this into the seeds.rb file and put the CSV file into /public/seed_data/zip_code.csv. It's pretty self explanatory (i.e., the csv has three columns: code, long. and lat.

    The code parses each line, extracts the pertinent data and assigns it to a local variable then writes it to a record. Hope it helps.

    File.open("#{Rails.root}/public/seed_data/zip_code.csv") do |zip_codes|
      zip_codes.read.each_line do |zip_code|
        code, longitude, latitude = zip_code.chomp.split(",")
        #  to remove the quotes from the csv text:
        code.gsub!(/\A"|"\Z/, '')
        # to create each record in the database
        ZipCodeGeo.create!(:zip_code => code, :longitude => longitude, :latitude =>      latitude)             
      end
    end
    

提交回复
热议问题