A simple way to seed a database in Rails

Creating default data into the database is very important before you write tests for backend, it’s called seeding.

I am going to share the way I did to add initial content after the database was created.

You can create seed data inside of db/seed.rb file, this file contains all the record creation needed to seed the database with its default values.

I have two models, the Destination model the Comment model, the destination has many comments.

The first step, list all the table names and then call `.destroy_all`, prepend db/seed.rb file with it will clear out all your destinations and comments record.

The second step, define the array to store all the created projects

Instead of defining each record, for example

You might want dynamically generate the record you need:

And to create some comments under destination, each method will help you iterate over destinations, create the new comment with a destination_id attribute and set it to destination.id

The third step, load the data and run the command in your terminal

`rails db:seed`

Last but not least, please go to the database administrator to view the table data, make sure you seed it successfully.

Here is a pgAdmin4 table data view since I am using Postgres SQL to store my application data.

And If you are using SQLite as your storage application, the DB browser for SQLite might be a good choice to view your table data.

Extension reading:

How do I view data in pgAdmin 4

How to use faker to generate seed data

https://medium.com/@gregadiaz89/lets-use-faker-to-generate-seed-data-6c6a0a6d10e

--

--

--

Full-Stack Web Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

EMOJO Mental Health Chatbot

4 Rules of Thumb for Providing Effective Code Review Feedback

What We Learned Using Elasticsearch as a Time Series Database

Load Local html file into WebView in Flutter. Call JS function from Flutter.

Count Number of Texts

Writing Clean Code With Swift — 7 Essential Tips!

5 RSpec strategies to get 95% test coverage or better

Is the Low-Code Development Hype Cycle Heading for A Crash?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Grace(Ge) Tian

Grace(Ge) Tian

Full-Stack Web Developer

More from Medium

Sarcophagus — A revolutionary evolution of value bonded contract

Which Are The Best Hybrid App Development Frameworks In 2022

Analyze a statement using the QFT framework

Ryukai Dev Blog #4 — New designs