我想将数据从CSV文件导入到现有的数据库表中。我不想保存CSV文件,只是从它的数据,并把它放入现有的表。我使用Ruby 1.9.2和Rails 3。

这是我的桌子:

create_table "mouldings", :force => true do |t|
  t.string   "suppliers_code"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "name"
  t.integer  "supplier_id"
  t.decimal  "length",         :precision => 3, :scale => 2
  t.decimal  "cost",           :precision => 4, :scale => 2
  t.integer  "width"
  t.integer  "depth"
end

你能给我一些代码,告诉我最好的方法,谢谢。


当前回答

使用这个宝石: https://rubygems.org/gems/active_record_importer

class Moulding < ActiveRecord::Base
  acts_as_importable
end

那么你现在可以使用:

Moulding.import!(file: File.open(PATH_TO_FILE))

只要确保标题与表的列名匹配即可

其他回答

你可以试试Upsert:

require 'upsert' # add this to your Gemfile
require 'csv'    

u = Upsert.new Moulding.connection, Moulding.table_name
CSV.foreach(file, headers: true) do |row|
  selector = { name: row['name'] } # this treats "name" as the primary key and prevents the creation of duplicates by name
  setter = row.to_hash
  u.row selector, setter
end

如果这是您想要的,您还可以考虑从表中删除自动递增的主键,并将主键设置为name。或者,如果有一些组成主键的属性组合,则将其用作选择器。不需要索引,这样会更快。

最好使用CSV::Table并使用String。编码(universal_newline:真)。它将CRLF和CR转换为LF

yfeldblum回答的简单版本,更简单,也适用于大文件:

require 'csv'    

CSV.foreach(filename, headers: true) do |row|
  Moulding.create!(row.to_hash)
end

不需要with_indifferent_access或symbolize_keys,也不需要先将文件读入字符串。

它不把整个文件一次保存在内存中,而是逐行读取,每行创建一个Moulding。

require 'csv'    

csv_text = File.read('...')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
  Moulding.create!(row.to_hash)
end

最好将数据库相关的进程包装在事务块中。代码片段blow是将一组语言播种到语言模型的完整过程,

require 'csv'

namespace :lan do
  desc 'Seed initial languages data with language & code'
  task init_data: :environment do
    puts '>>> Initializing Languages Data Table'
    ActiveRecord::Base.transaction do
      csv_path = File.expand_path('languages.csv', File.dirname(__FILE__))
      csv_str = File.read(csv_path)
      csv = CSV.new(csv_str).to_a
      csv.each do |lan_set|
        lan_code = lan_set[0]
        lan_str = lan_set[1]
        Language.create!(language: lan_str, code: lan_code)
        print '.'
      end
    end
    puts ''
    puts '>>> Languages Database Table Initialization Completed'
  end
end

下面的代码片段是languages.csv文件的一部分,

aa,Afar
ab,Abkhazian
af,Afrikaans
ak,Akan
am,Amharic
ar,Arabic
as,Assamese
ay,Aymara
az,Azerbaijani
ba,Bashkir
...