從控制檯命令上傳 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'

現在開啟你的開發 consolerun

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