paint-brush
How to Seed Your Rails Database with Faker by@adebola
1,128 reads
1,128 reads

How to Seed Your Rails Database with Faker

by Adebola AdeniranJune 28th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

How to Seed Your Ruby-on-Rails Database with Faker. Faker is a way to generate users that have tickets and also have comments without having to manually type in a value for each field. The Faker attributes you can use are all available from the faker GitHub page. The faker gem is required to seed the database and create Users using fake data from the Faker gem. The seed seed is used to generate a random number between 1 and 20 to test your application.

People Mentioned

Mention Thumbnail
featured image - How to Seed Your Rails Database with Faker
Adebola Adeniran HackerNoon profile picture

I built a Customer Support System a few days ago and started to think of a way to seed my rails database with random data for testing without having to manually type in the data. This may not be the best way to do it, but it works and allows you to test your application.

We want a way to generate users that have tickets and also have comments without having to manually type in a value for each field.

Let's start with the basic schema of the DB.

Our Database, schema and migrations have already been generated and the main focus here will be on seeding the database.

First, install the faker gem by adding it to your list of gems in your gemfile.

gem 'faker'

then run

bundle install

Once done, head into your seeds.rb file inside the db directory. In here, require the faker gem at the beginning.

require 'faker'

Next, let's create Users using fake data from the

faker gem
.

The Faker attributes you can use are all available from the faker GitHub page.

role: %w[customer admin agent].sample # a user can have only one of these roles

The line above may look a little strange — we’ve designed our model to only accept one of the values in [“customer”, “admin”, “agent”] as the
values assigned to role for users. calling

.sample
on the array causes the code to select one of the three possible values.

I’ve added some comments using the # symbol beside the lines.

Next, let’s create Tickets. Remember that each ticket belongs to a User. As such, we’ll need to find a way to assign tickets to users randomly.

The line above is used to generate a random number between 1 and 20. Recall that our users were assigned Id’s between 1 and 20.

Finally, let’s generate comments that belong to a User and is tied to a ticket.

Once done, simply run

rails db:seed

You can check that everything went well by checking your rails console.