Ruby on Rails - 从 CSV 文件导入数据 [英] Ruby on Rails - Import Data from a CSV file

查看:31
本文介绍了Ruby on Rails - 从 CSV 文件导入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to import data from a CSV file into an existing database table. I do not want to save the CSV file, just take the data from it and put it into the existing table. I am using Ruby 1.9.2 and 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

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

Can you give me some code to show me the best way to do this, thanks.

推荐答案

require 'csv'    

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

这篇关于Ruby on Rails - 从 CSV 文件导入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆