ruby on rails - Import CSV files into SQL database in ROR -
i've searched similar thread no luck far, building ror application , have create database, want import css file database, below files have errors got:
schema.rb:
activerecord::schema.define(version: 20170913210926) create_table "items", force: :cascade |t| t.string "title" t.string "description" t.string "author" t.string "tags" t.datetime "created_at", null: false t.datetime "updated_at", null: false end end
i have rake task file(import.task):
require 'csv' csv_text = file.read('/path/to/csv/item.csv') csv = csv.parse(csv_text, :headers => true) csv.each |row| item.create!(row.to_hash) end
so when ran rake import.task in terminal got following error:
rake aborted! nameerror: undefined local variable or method `item' main:object
your rake task looks more regular ruby script rake task. if want use rake this, try like:
require 'csv' namespace :import desc 'imports csv data db' task from_csv: :environment csv_text = file.read('/path/to/csv/item.csv') csv = csv.parse(csv_text, :headers => true) csv.each |row| item.create!(row.to_hash) end end end
and invoke rake import:from_csv
Comments
Post a Comment