從控制檯命令上傳 CSV

終端命令:

 placeholderCopyrails g model Product name:string quantity:integer price:decimal{12,2}
rake db:migrate

Lates 建立控制器。

終端命令:

 placeholderCopyrails g controller Products

控制器程式碼:

 placeholderCopyclass 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

模型:

 placeholderCopyclass Product< ApplicationRecord
  def self.import(file)
      CSV.foreach(file.path, headers: true) do |row|
          Product.create! row.to_hash
      end
  end
end

routes.rb

 placeholderCopyresources :products

應用程式/配置/ application.rb 中

 placeholderCopyrequire 'csv'

現在開啟你的開發 consolerun

 placeholderCopy=> ProductsController.new.create #=> Uploads your whole CSV files from your folder directory