Ruby on Rails - upload csv from console command in ruby on rails- ruby on rails tutorial - rails guides - rails tutorial - ruby rails
upload csv from console command
Terminal Commands:
rails g model Product name:string quantity:integer price:decimal{12,2}
rake db:migrate
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
Lates create controller. Terminal Commands:
rails g controller Products
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
Controller Code:
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
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
Model:
class Product< ApplicationRecord
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Product.create! row.to_hash
end
end
end
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
routes.rb
resources :products
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
app/config/application.rb
require 'csv'
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
Now open your development console & run
=> ProductsController.new.create #=> Uploads your whole CSV files from your folder directory