Creating A Seed File In Rails

The purpose of creating a seed file in short is to populate sample data in your rails database. Having prepopulated data helps us test our application and better understand how it will look in production.

When creating a Rails application a seed file is created within the db directory and it’s named seeds.rb. By default, this file will have no code in it however Rails helpfully provides some clarification of its purpose.

# This file should contain all the record creation needed to seed the database with its default values.# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).## Examples:##   movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])#   Character.create(name: 'Luke', movie: movies.first)

It would be rather tedious creating data one model at a time so it’s common practice to populate data with loops. Below we can see an example of a blog that has two fields “title” and “body”, it is useful to have your project schema open whilst doing so you have reference to your field names.

Once we have our loop in place you may wonder how do we run this code? Two common options are as follows…

rails db:setup

rails db:setup wipes all preexisting data from out database and repopulates it with our seeds. However, if you want to preserve your existing data and simply add your seeds on top of it you can simply run…

rails db:seed

Now to check our new data has been added run the rails console with the command:

rails c

Following this enter the name of your model followed by the count method, for example, for a model with the name “blogs” we would run:


Hi, I’m Steven, most call me Steve! I’m a programmer, musician, and artist. This blog contains various tutorials and posts related to software development.

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