Comma Separated Values (CSV) files represent some commonly used files. You may have a CSV file generated from a report generated, and then you may need to write a Ruby method or task to insert it into the database.
Before we start, we need to make sure that the first line in the CSV file (the header line) has the same name as the column names of our respective model.
Let’s start to implement this.
First we need to import CSV in our Ruby:
We can then set up the file path, which we will use as an argument inside CSV’s foreach method. Then we can simply open and iterate through each file line, convert them into a hash and do the insertion in the database:
path = Rails.root.join('lib', 'seeds', "Documents.csv") CSV.foreach(path, :headers => true, encoding: "UTF-8") do |row| Model.create(row.to_hash)#Model is the name of your model end
This is all we need to do to insert a CSV file into database. I have also used the UTF-8 encoding, as one of the most widespread ones and also the one that covers a wide range of characters.
Bonus tip: If you open a CSV file in Microsoft Excel, chances are that its structure may change. In several recent cases, three different CSV files that I opened were changed internally simply because they were opened in Microsoft Excel. Their commas were replaced with spaces, which was something I did not expect. The solution for modifying my CSV files before inserting them in the database was to edit them using another text editor.