In this article, you will learn how to seed a database in Ruby on Rails.
Seeding a Database
Seeding a database in Ruby on Rails involves populating the database with initial data that can be used for testing or setting up default values for an application. Here are the steps to seed a database in Ruby on Rails:
Create a seeds.rb file
In the root directory of your Rails application, create a file called seeds.rb. This file will contain the code that will populate your database with data.
Add data to the seeds.rb file
In the seeds.rb file, use Ruby code to create and save data to the database. For example, you can create a new user by writing
User.create(name: "John Doe", email: "email@example.com").
Run the seed command
In the terminal, navigate to the root directory of your Rails application and run the command rails db:seed. This will execute the code in the seeds.rb file and populate your database with the data you specified.
Verify the data
To verify that the data has been seeded correctly, you can use Rails console to check the database entries. Run the command rails console in the terminal to open the console, and then run a query to retrieve the seeded data, such as User.all.
Here’s an example of what a seeds.rb file might look like:
# Seed some users User.create(name: "John Doe", email: "firstname.lastname@example.org") User.create(name: "Jane Doe", email: "email@example.com") # Seed some products Product.create(name: "Widget", price: 9.99) Product.create(name: "Gizmo", price: 14.99)
When you run rails db:seed, this code will create two users and two products in the database. You can then use Rails console to verify that the data has been seeded correctly.