see

Seeding Afresh: Rails db:seed:replant

Alessio Bussolari
3 min readNov 3, 2023

--

Seeding a database in Rails is a common task that developers perform regularly. When building an application, it’s often necessary to reset the database to a clean state and populate it with initial data. This is especially true in the development and testing phases. With the introduction of `rails db:seed:replant`, this process has been simplified, allowing developers to reseed the database with one command. This replaces the older method of dropping, creating, migrating, and then seeding the database.

Before diving into the specifics of the `db:seed:replant` command, let’s understand the context and the commands it replaces:

Context: Database Seeding in Rails

Rails uses a `seeds.rb` file located in the `db` directory, which is a conventional place to put all the seeding logic. Seeding the database is usually done through the `rails db:seed` command. However, there might be times when you want to start afresh, which traditionally involved multiple steps:

rails db:drop db:create db:migrate db:seed

These steps are necessary to clear out the old data and ensure that the new data is built on a clean slate.

Introducing `db:seed:replant`

The `db:seed:replant` rake task was introduced to consolidate these steps into one. Here’s how it works:

  • Drop Database: The existing database is dropped, removing all data and schema.
  • Create Database: A new instance of the database is created.
  • Migrate Database: The database migrations are run, setting up the schema.
  • Seed Database: Finally, the seed data is loaded into the database.

The primary advantage of this command is its simplicity and speed, making it ideal for rapid development cycles.

Using `db:seed:replant` in a Rails Project

Here’s a simple example in a Rails project where you might use `db:seed:replant`:

# Inside seeds.rb
User.create(name: "John Doe", email: "john.doe@example.com")
Product.create(name: "Gadget", price: 99.99)

--

--

Alessio Bussolari

Ruby on Rails programmer since 2009. Current CTO at COSMIC SRL, where I lead the team in creating innovative solutions.