簡體   English   中英

如何通過rake任務導入CSV文件?

[英]How can I import a CSV file via a rake task?

我知道這個問題已經在這個論壇上被問了很多,但是我在一個嚴格的截止日期前,我需要一些幫助,所以任何建議都非常感謝。 我是Ruby on Rails的新手,所以請在回復時記住這一點。 我想創建一個rake任務,在運行時,更新mysqlite db中的多個表。 這是一個在我的數據庫中創建新事件的遷移文件。 如何創建rake任務,通過CSV文件輸入所有這些信息。 有人可以從頭到尾寫一些rake文件給我一些幫助。 顯然你不需要為每個字符串編寫每個任務,只需舉幾個例子。 除了實際的rake文件,我是否需要將代碼添加到我的應用程序的任何其他部分(我知道這是一個非常一般的問題,但如果我確實需要添加代碼,我將非常感謝在哪里進行一般描述)。 我覺得會有一些指導意見。 如果有人需要我的任何更多信息,請詢問。

class CreateIncidents < ActiveRecord::Migration
  def self.up
    create_table :incidents do |t|
      t.datetime :incident_datetime
      t.string :location
      t.string :report_nr
      t.string :responsible_party
      t.string :area_resident
      t.string :street
      t.string :city
      t.string :state
      t.string :home_phone
      t.string :cell_phone
      t.string :insurance_carrier_name
      t.string :insurance_carrier_street
      t.string :insurance_carrier_city
      t.string :insurance_carrier_state
      t.string :insurance_carrier_phone
      t.string :insurance_carrier_contact
      t.string :policy_nr
      t.string :vin_nr
      t.string :license_nr
      t.string :vehicle_make
      t.string :vehicle_model
      t.string :vehicle_year


      t.timestamps
    end
  end

  def self.down
    drop_table :incidents
  end
end

在lib / task的項目文件夾下創建一個rake文件,說“import_incidents_csv.rake”

遵循這個Ruby on Rails - 從CSV文件導入數據

在rake文件中有以下代碼

require 'csv'
namespace :import_incidents_csv do
  task :create_incidents => :environment do
    "code from the link"  
  end
end 

您可以將此任務稱為“rake import_incidents_csv:create_incidents”

我有一天工作了幾個小時。 我終於通過執行以下操作來實現它:

  1. 在我的csv文件的第一行添加了一個標題,反映了我的模型中的attr_accessible 在我的情況下,我的模型是attr_accessible :intro:name和我的csv文件中的第一行讀取名稱,簡介。
  2. 創建了自定義rake文件。 我將我的命名為import.rake並將其放在lib / tasks文件夾中。 將此代碼放在該文件中:
 #lib/tasks/import.rake require 'csv' desc "Imports a CSV file into an ActiveRecord table" task :import, [:filename] => :environment do CSV.foreach('myfile.csv', :headers => true) do |row| MyModel.create!(row.to_hash) end end 

然后在命令行中鍵入bundle exec rake import

為了使這個工作,我有相當SQLite數據庫瀏覽器。 我希望能幫助別人!

這是我使用rake db:seed導入的示例CSV。 我將其寫入seeds.rb文件並將CSV文件放入/public/seed_data/zip_code.csv。 它非常自我解釋(即,csv有三列:代碼,long。和lat。

代碼解析每一行,提取相關數據並將其分配給局部變量,然后將其寫入記錄。 希望能幫助到你。

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

您可以使用rails的CSV模塊讀取csv文件,並可以創建記錄。 以下是詳細的幫助: 使用csv填充數據庫

我過去曾經用過這個。 它需要任何類型的模型。

rake csv_model_import [bunnies.csv,Bunny]

奇跡般有效。

 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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM