从控制台命令上传 CSV
终端命令:
rails g model Product name:string quantity:integer price:decimal{12,2}
rake db:migrate
Lates 创建控制器。
终端命令:
rails g controller Products
控制器代码:
class HistoriesController < ApplicationController
def create
file = Dir.glob("#{Rails.root}/public/products/**/*.csv") #=> This folder directory where read the CSV files
file.each do |file|
Product.import(file)
end
end
end
模型:
class Product< ApplicationRecord
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Product.create! row.to_hash
end
end
end
routes.rb
resources :products
应用程序/配置/ application.rb 中
require 'csv'
现在打开你的开发 console
&run
=> ProductsController.new.create #=> Uploads your whole CSV files from your folder directory