Lets suppose that a file named product.csv exists into db folder in our applications. To import this file we will create file import.rake in my_app/lib/tasks/.
The import.rake file looks like...
require 'csv'
desc "Import product from csv file"
task :import => [:environment] do
file = "db/product.csv"
CSV.foreach(file, headers: true) do |row|
product_hash = row.to_hash
product = Product.where(id: product_hash["id"])
if product.count == 1
product.first.update_attributes(product_hash)
else
Product.create!(product_hash)
end
end
end
The above code reads the row from browsed csv file and inserting it to table products if record not in table, if the record exist then it'll update.
The contents of a csv file which one to be import
Path: my_app/product.csv
id,name,quantity,price
1,prod1,15,150
2,prod2,10,300
3,prod3,23,456
4,prod4,13,45
5,prod5,145,36
6,prod6,12,34
7,prod7,5,99
8,prod8,19,39
9,prod9,45,900
Go to rails console and run command
rake import
Finally check your products table, you will see the csv file data in to table.
0 Comment(s)