Uploads CSV from console command

suggest change

Terminal 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents