How to seed your Rails database using Faker Gem, CSV file, JSON file, and third-party APIs

Chi Nguyen
4 min readApr 19, 2021

--

You may scare if the endpoint of an API you are working on for your final project could break. You may have the CSV file that contains all the data you want to use. But you don’t know how to seed to your Rails database to produce your own APIs.

This article will help you have more ways to seed a huge amount of data to your Rails application.

I will create a Github repo for anyone interested in this article can easier following. All the code and guidance are in the “seeds.rb” file of the Rails app. Our app will have a table name “wizard”. Our purpose is to try to create thousand of wizards for building out our own APIs.

1. FAKER gem (sources)

FAKER gem is a library that can generate fake data. To install it, you can go to your Rails app directory terminal and run “gem install faker” or add faker gem in your Gemfile file, then run “bundle install” (below picture)

FAKER library contains thousands of categories that can help you generate random data. For example, I can go to this page to see how to use the FAKER to generate wizards in Harry Potter movies. Below is the way to generate one wizard for our database.

As you can see, I use Faker::Movies::HarryPotter to generate the name of the wizard, use Faker::Date to generate the fake birthday of that wizard. Then using Faker::Color to have the random hair color.

If you want to generate 1,000 wizards, just using the Time Loop method for an automatic seeding database.

Now run “rails db:seed” to seed the database again and run “rails c” to check if we get 1000 wizards

Great! We have 1000 wizards for testing purposes now.

2. CSV file (download here for testing)

Download the “hp_characters.csv” file and put it in the “db” folder inside your app.

In Rails, it has a library name “csv” which helps you to read the CSV file. Remember to add “require ‘csv’ ” in your seeds.file as below

The “row” variable in the above code is each row in our CSV file. row[‘Column_name”] is the value of that Column name in each row. For example, the first run in this loop is the first row in the CSV table. At this moment, the row[‘Name’] = “Harry James Potter”.

We can check in “rails c”.

Our CSV file contains 140 rows. When the code running, it will generate 140 wizards in the Rails database.

3. JSON file (download here for testing)

Download the “hp_characters.json” file and put it in the “db” folder inside your app.

Use “JSON.parse” method to read the JSON file. As you can see inside our JSON file is an array contains 140 elements(which contains a wizard’s information). Use each method to iterate through the array. Each element will create a new wizard in the Rails database.

Go to “rails c” to check our database.

4. External APIs (link)

--

--

Chi Nguyen
Chi Nguyen

No responses yet