If you are building a webapp with Ruby on Rails, you will maybe have the need to load data, so here is a good way to insert data in the database, using a csv file and couple lines of code.
project/db/seed.rd file of your project and adding this few lines.
CSV.foreach(Rails.root.join('path/file.csv'), headers: true) do |row|
CSV This class provides a complete interface to CSV files and data. It offers tools to enable you to read and write to and from Strings or IO objects, as needed. Source.
Rails.root.join represents a pathname which locates a file in a filesystem,
headers: true we are specifying that the source file have a header and will ignore the first row, in case we don’t have a header just turn to
false the option.
Then lets indicate the corresponding field of our table where will insert with.
For complete with the seed, run in the terminal
$ bundle exec rake db:seed
The final code should look like:
CSV.foreach(Rails.root.join('path/to/file.csv'), headers: true) do |row|
Model.create! do |model|
mode.fiel1 = row
mode.fiel2 = row
mode.fiel3 = row
mode.fiel4 = row