如何通过rake任务导入CSV文件?

我知道这个问题已经在这个论坛上被问了很多,但是我在一个严格的截止日期之前,我需要一些帮助,所以任何建议都非常感谢。 我是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有三列:代码,长和。纬度。

代码解析每一行,提取相关数据并将其分配给局部变量,然后将其写入记录。 希望能帮助到你。

 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 
Interesting Posts