Ruby on Rails, seed, gem Faker — generation of fake datas

Oleksii Voitsekhovych
2 min readSep 2, 2022

In the previous article, we considered how using STI and belongs_to — to create models and a data structure for storing addresses. In this article, we will consider how to generate some data for further experimentation with the help of gem Faker. Let’s start.

To begin with, a little theory.

First, the seed mechanism is used to generate start data in Ruby on Rails projects. What it is:

To add initial data after a database is created, Rails has a built-in ‘seeds’ feature that makes the process quick and easy. This is especially useful when reloading the database frequently in development and test environments. It’s easy to get started with this feature: just fill up db/seeds.rb with some Ruby code, and run rails db:seed

That is, in the seeds.rb file — we write the usual ruby ​​code — which will be executed and do what we need.

Next, what is gem Faker.

A library for generating fake data such as names, addresses, and phone numbers.

That is, with the help of this gem, you can generate data for yourself, which at first glance will look like real data. There are a lot of data types — you can view all of them here — https://github.com/faker-ruby/faker#generators

Well, we will use Faker::Address, and specifically in our case we will use: Faker::Address.state_abbr, Faker::Address.city, Faker::Address.street_name.

Well, let’s write the code.

We write the following in the file db/seeds.rb

seeds.rb

What are we doing here? First, we delete all data. then add 10 states, 10 cities in each state, and 10 streets in each city.

rails db:seed

Well, of course we check with our old method :)

p ActiveRecord::Base.connection.exec_query(‘select * from address_parts’)

That’s all. We have a datas to work with addresses. And in the next article, we will talk about how to use Rails and Stimulus to show 3 select boxes in which related data will be dynamically loaded.

--

--