2012-09-17 74 views
21

我知道這個問題已經在這個論壇上問了很多,但我在嚴格的最後期限,我需要一些幫助,所以任何意見是非常感激。我是Ruby on Rails的新手,所以在回覆時請記住這一點。我想創建一個rake任務,在運行時更新mysqlite db中的多個表。這是一個遷移文件,在我的db中創建一個新的事件。如何創建一個rake任務,通過CSV文件輸入所有這些信息。有人可以給我一些幫助,從頭到尾編寫耙文件。顯然,你不需要爲每個字符串編寫每個任務,只給我幾個例子。除了實際的rake文件,我是否需要將代碼添加到我的應用程序的任何其他部分(我知道這是一個非常普遍的問題,但如果確實需要添加代碼,我將不勝感激一般的描述)。我覺得有一點指導會順利進行。如果有人需要我提供更多信息,請提問。如何通過rake任務導入CSV文件?

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 
+0

這是有益.... > http://stackoverflow.com/questions/3346108/how-to-write-rake-task-to-import- data-to-rails-app –

回答

20
中的lib /任務的項目文件夾下創建

耙文件說 「import_incidents_csv.rake」

關注該 Ruby on Rails - Import Data from a CSV file

在耙文件

有下面的代碼

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

您可以將此任務稱爲「rake import_incidents_csv:create_incidents」

+0

我的問題是,我不知道放入rake文件的代碼是否正確地創建了新的事件,沒有任何錯誤。但謝謝你的迴應。 – RubyDude1012

+0

您需要創建一個帶有第一行的csv文件作爲事件表的列名。 – Rubyman

+0

這是我在StackOverflow上找到的代碼,我嘗試去適應我的應用程序。我無法得到它格式化雖然讀...對不起desc「的一號線任務描述」 任務:import_csv做 需要「CSV」 csv_text = File.read('C:/導軌/拇指/ incidents.csv') csv = CSV.parse(csv_text,:headers => true) csv.each do | row | 行= row.to_hash.with_indifferent_access Incidents.create!(row.to_hash.symbolize_keys) 結束 結束 – RubyDude1012

2

這是我使用rake db導入的一個CSV示例:seed。我將它寫入了seeds.rb文件,並將CSV文件放入/public/seed_data/zip_code.csv。這是相當自我解釋(即,CSV有三列:代碼,長和經緯度

該代碼解析每一行,提取有關的數據,並將其分配給一個局部變量,然後寫入一個記錄。幫助

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 
11

我從事這幾個小時有一天,我終於得到它通過執行以下工作:。在第一行

  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數據庫瀏覽器。我希望能幫助別人!

0

您可以使用rails的CSV模塊來讀取您的csv文件,並可以創建記錄。這裏有詳細的幫助:Populate db using csv

0

我以前用過這個。它需要任何類型的模型。

rake csv_model_import [bunnies。csv,兔子]

工程就像一個魅力。

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

+0

不好的樣本,因爲逗號 –