Manually Seed Data in Ruby No More!

Peter Viss
4 min readJun 6, 2019

--

The purpose of this blog is to show specifically how to use the ‘faker’ gem in Ruby Sinatra.

How many of you have ever needed to take a long time to seed data into your database manually for Ruby? For the last week and a half I know I have. It was not until recently that I discovered there is a faster and better way to seed your data using the ‘faker’ gem. You are able to use this gem in Ruby with Sinatra and Ruby with Rails. It honestly has saved me so much time since I discovered what it can do.

What it Does

The ‘faker’ gem generates specific, fake seed data using its own databases so you can populate your own database.

Downloading and Requiring ‘Faker’

Before using the ‘faker’ gem, we need to be able to install it using our terminal or whatever text editor you use.

If you are already have a Gemfile all you need to do is add the ‘faker’ gem to the list of gems you are using and do a bundle update in your terminal.

Example 1:

Atom Text Editor using a Gemfile

If you decide to go to use your terminal all you need to do is put gem install faker and it will install into your program.

Example 2:

After the ‘faker’ gem is installed you will need to require the gem in your text editor. There are a number of places you can require ‘faker’, but the easiest is to just do it on top of your seeds file.

Example 3:

Using ‘Faker’ Effectively

To get the most out of using ‘faker’, you need to be able to label and correctly implement the syntax. Fortunately for us, the gem makes it pretty simple.

The first part you need to do is define how many times you want ‘faker’ to create the specific seeds you are putting in your database.

In the example below you will see that I decided to create a guest object with a unique name as well as a show object with a unique band name and a unique city. Since I had a many-to-many relationship, I decided to have a join table that would take in a guest and a show that was created. Specifically, I used their id to identify them with the database since the name is just a string and the database relates to the id number.

Example 4:

WARNING: .UNIQUE HAS A LIMIT ON HOW MANY TIMES YOU CAN CALL ON IT DEPENDING ON THE TOPIC.

As you can see below, when I tried to create 1000 unique band names the rake was aborted because that specific ‘faker’ file did not have enough unique names to satisfy my request. After I took the unique out my file was able to be seeded.

Example 5:

Resources to Use

The ‘faker’ gem has many files you can use. The range from kinds of coffee, to Pokémon data.

Conclusion

My hope is that you are able to get as much out of this gem as possible like I have and I am going to keep doing.

Here is the link to be able to see what kind of files and other features the ‘faker’ gem has to offer. https://github.com/stympy/faker/blob/master/README.md

--

--