简体   繁体   English

Rails:CSV导入

[英]Rails: CSV Import

i genereated an csv with columns id, task, description, created_at, updated_at 我生成了具有列ID,任务,描述,created_at,updated_at的csv

 create_table "tasks", :force => true do |t|
t.string   "task"
t.string   "description"
t.datetime "created_at",   :null => false
t.datetime "updated_at",   :null => false

I opened the sqlite Konsole 我打开了sqlite Konsole

   rails db
   .separator ','
   .C:/User/jkl/Desktop/tasks.csv

I get error datatype mismatch. 我得到错误数据类型不匹配。 I dont fill in created_at and updated_at, but this is from rails to null => false. 我没有填写created_at和updated_at,但这是从rails到null => false。

How do you import? 您如何汇入?

I usually do it via a ruby script: 我通常通过ruby脚本来做到这一点:

require 'csv'

def import
  CSV.foreach('path/to/file.csv', :col_sep => ';', :headers => true) do |row|
    Task.create!(row.to_hash)
  end
end

This works assuming your CSV headers match your column names, like so: 假设您的CSV标头与您的列名匹配,这可以正常工作,如下所示:

task;description
"Task 1";"Paint the fence"

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM