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

Rub*_*012 21 rake ruby-on-rails import-from-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
Run Code Online (Sandbox Code Playgroud)

Rub*_*man 20

在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 
Run Code Online (Sandbox Code Playgroud)

您可以将此任务称为"rake import_incidents_csv:create_incidents"


lfl*_*res 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
Run Code Online (Sandbox Code Playgroud)

然后键入bundle exec rake import命令行.

为了使这个工作,我有相当SQLite数据库浏览器.我希望能帮助别人!