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

21

我知道这个问题在论坛上已经被问过很多次,但是我面临紧迫的截止日期,需要一些帮助,所以任何建议都非常感激。我是Ruby on Rails的新手,请谨记这一点。我想创建一个rake任务,当运行时,会更新mysqlite数据库中的多个表。这是一个迁移文件,它在我的数据库中创建了一个新的事件。如何创建一个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

这很有帮助...
https://dev59.com/zE_Sa4cB1Zd3GeqP_13r
- Gopal S Rathore
5个回答

21

在您的项目文件夹下的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”。

我的问题是我不知道在rake文件中应该放置哪些代码才能正确创建新的事件而没有任何错误。但还是谢谢你的回复。 - RubyDude1012
您需要创建一个 CSV 文件,其中第一行为事件表的列名。 - Rubyman
这是我在StackOverflow上找到的代码,我试图将其适应我的应用程序。但我遇到了格式问题,很抱歉... desc "一行任务描述"task :import_csv dorequire 'csv'csv_text = File.read('c:/rails/thumb/incidents.csv') csv = CSV.parse(csv_text, :headers => true) csv.each do |row| row = row.to_hash.with_indifferent_access Incidents.create!(row.to_hash.symbolize_keys) endend - RubyDude1012
抱歉,Rubyman,我误读了你的回复。我进行了调整,导入成功了!!!非常感谢您给我提供了一个起点来更新我的内容。您不知道您帮了我多少忙……如果您没有察觉到的话,我有点慌张。再次感谢!!! - RubyDude1012
如果这个答案对您有帮助,请接受它,这样我就能获得一些声望点。 :) - Rubyman
显示剩余2条评论

11

我曾经在一天中花费了数小时的时间进行工作。最终,通过以下方法使其工作:

  1. 在我的 CSV 文件的第一行中添加了一个标题,反映了我模型中的 attr_accessible。在我的情况下,我的模型是 attr_accessible :intro:name,并且在我的 CSV 文件中,第一行读取 name、intro。
  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数据库浏览器。希望这能对某些人有所帮助!

2
这是一个使用rake db:seed导入的CSV示例。我将其编写到seeds.rb文件中,并将CSV文件放入/public/seed_data/zip_code.csv。它相当容易理解(即,csv有三列:code、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

0
您可以使用Rails的CSV模块读取CSV文件并创建记录。这里是详细的帮助文档:使用csv填充数据库

0

我以前用过这个。它可以接受任何类型的模型。

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


坏样本,因为有逗号。 - animekun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接