Uploads CSV from console command
suggest changeTerminal commands:
rails generate model Product name:string quantity:integer price:decimal{12,2}
rails db:migrate
Next, create the controller.
rails generate controller Products
Dir.glob returns path strings. Pass each path to the model; a string has no path method.
class ProductsController < ApplicationController
def create
Dir.glob(Rails.root.join("public/products/**/*.csv")).each do |path|
Product.import(path)
end
end
end
Model:
class Product < ApplicationRecord
def self.import(path)
CSV.foreach(path, headers: true) do |row|
Product.create!(row.to_hash)
end
end
end
config/routes.rb
resources :products
config/application.rb
require "csv"
From the development console, call the model. ProductsController.new.create has no request, so it is the wrong entry point here:
Dir.glob(Rails.root.join("public/products/**/*.csv")).each do |path|
Product.import(path)
end
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents