[英]How to import CSV to Rails app
Rails 4.1.7 Ruby 2.1.4
我正在嘗試通過控制器方法將CSV文件上傳到我的應用程序:
的routes.rb
get 'csv_upload', to: 'users#csv_upload'
users_controller.rb def csv_upload
require 'csv'
customers = CSV.read('customers.csv')
customers = CSV.parse(csv_text, :headers => true)
customers.each do |row|
Moulding.create!(row.to_hash)
end
redirect_to users_url
end
CSV文件customer.csv
gender ,age
10,20
11,20
12,20
13,20
14,20
15,20
它位於根目錄上。 這是我得到的錯誤:
Errno::ENOENT in UsersController#csv_upload
No such file or directory @ rb_sysopen - customers.csv
Extracted source (around line #72):
70
71
72
73
74
75
customers = CSV.read('customers.csv')
customers = CSV.parse(customers, :headers => true)
Rails.root: /Users/andreucasadella/rails_projects/hackcdmx
例外情況是找不到該文件。
customers = CSV.read('customers.csv')
是相對路徑。 它在當前工作目錄中搜索文件(可能並不總是在根目錄中)。 您可以使用以下方法檢查工作目錄:
raise Dir.getwd.to_s
customers = CSV.read('customers.csv')
並且會顯示一個例外,顯示您正在搜索的文件中的當前文件夾。
為了避免這種情況,您最好直接使用Rails.root
指定路徑,例如:
customers = CSV.read(Rails.root.join('customers.csv'))
我終於有了一個任務:
LIB /任務/ task.rake
namespace :tasks do
require 'csv'
desc "cargar usuarios"
task :load_usuarios => :environment do |t, arg|
user_files =['lib/datasets/customers.csv']
user_files.each do |user|
CSV.foreach(user,:headers => true) do |row|
id = row.to_hash['id']
gender = row.to_hash['gender']
age = row.to_hash['age']
User.create(id: id,gender: gender,age: age)
end
end
end
end
創建一個名為“數據集”的文件夾,並將文件“ customer.csv”保存在此處:
app/lib/datasets/customer.csv
然后通過終端執行任務
rake tasks:load_usuarios
繁榮! 准備
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.