Seeding a PostgreSQL Database

Melissa Gonzalez
Adventures in Code
Published in
5 min readAug 21, 2017

How to Populate a New Rails App with Sample Data

In order to build out a newly-made Rails app, adding sample data to the database is an important step for testing how the app will look and work. After creating your app, creating a database, adding tables, and creating the appropriate associations between your tables, you are now ready to add sample data!

There are several ways you can go about adding data to your database. In this post, I’ll go over different methods we’ve used in class to add sample data to a PostgreSQL database in Rails.

Rails Console

The simplest way for a beginner to add data to their database is simply in the terminal using the rails console. In your terminal, navigate to your app folder, then enter the command rails console. This starts a Ruby testing environment with your app files installed.

To create instances of a specific model, use the new command to store the instance into a temporary variable, then save this instance to the database.

model = ModelName.create({attribute_1: “value_1”, 
attribute_2: “value_2”})
model.save

An alternative way to implement both commands in one line is to use the create function, which BOTH creates a new instance of your model AND ALSO saves it to the database.
ModelName.create({attribute_1: “value_1”, attribute_2: “value_2”})

If there are any issues with your models and associations, you will get a ROLLBACK error in your rails console. This commonly occurs when you have a belongs_to/ has_many relationship between two tables but don’t specify the appropriate id in the model that belongs_to.

You know you’re golden if you’re able to save data properly without any rollbacks!

The main benefit of adding data through the console is that it provides immediate feedback on whether your associations are solid, and you can test your associations fairly quickly. However, since you have to type all the information manually, this can become cumbersome if you want to be able to add a lot of seed data.

Postico

When you have a fair amount of seed data that you want to input quickly, a faster option is to use a program such as Postico to enter data in a manner more similar to using an Excel spreadsheet.

One drawback to using Postico, however, is that it’s only tied to the database itself, and not the Rails app (unlike the console). Because of this, it’s unable to perform functions specific to your Rails app, such as testing associations between tables and automatically generating id, created_at, and updated_at data for each instance.

The easiest way to get around some of these shortcomings is to generate blank instances of your model using the command `ModelName.create` several times via the Rails Console, then simply use Postico to manually enter in the values for the various attributes.

If the table you’re populating belongs_to another table, then make sure you include id numbers corresponding to instances of the associated table. Since Postico is not tied to the Rails App, it will NOT produce a rollback error if you enter data without the proper associations; however, you will get errors later one when you try manipulating this data within your app itself.

Seeds File

The most powerful way to input data into your database is using the Seeds file in Rails. However, this method also requires a strong foundation in Rails, particularly requires a solid understand in how database management and associations work.

The seeds file is located at db/seeds.rb and is simply a Ruby file that runs when the command rails db:seed is entered. Any code you write in the seeds file will run as if you were in the Rails Console. You can create as much data in your seeds file, but keep in mind that since it is running within your app, all the appropriate associations must be valid.

The drawback of the seeds file is that it’s harder to tell when there are errors since the file simply runs. If you get rollbacks, the data just doesn’t exist when viewing your database in Postico, so it may not be immediately clear what the error is.

It’s best to use your seeds file once you’ve already tested that your associations work in the Rails Console. If you do get errors when running your seeds file, you may need to delete (rails db:drop), re-create (rails db:create), re-migrate (rails db:migrate), and re-populate (rails db:seed) your database. Therefore, a working knowledge of how to perform these functions is necessary prior to using the seeds file.

You can also use the command rails db:reset to perform the delete, create, migrate, and seeds functions sequentially. However, since it is performing 4 actions in a row, you must be fairly proficient in managing these database tasks if any errors occur while performing these functions.

It’s important to note that using the commands rails db:drop and rails db:reset are irreversible, so only perform those functions if you are 100% sure that’s what you want to do.

Common errors that occur when implementing a seeds file include:

  • rollbacks due to not including the appropriate id attribute when one table belongs_to another
  • typos in the seeds file
  • mistakes in syntax within the seeds file
  • failure to create the appropriate associations

Here are a few things to check if your seeds file isn’t populating your database properly:

  • In the schema or migration file: does the appropriate column exist?
  • In the Model.rb file: are the belongs_to and has_many associations listed properly?
  • In the seeds file: did you assign the foreign key to each instance?
  • Did you spell all the attribute names correctly?
  • Do the attributes references in the seeds file match what’s in your schema file?
  • Do you have the syntax correct based on your associations?
    For example: you can only say user.events if:
    1. you define which user you’re talking about (user = User.first, etc)
    2. the User.rb contains has_many :events OR
    has_many :registrations AND has_many :events, through: :registrations

Once you’ve seeded your database, it’s easier to build out various features of your app, since it’s easier to tell if it’s working or not! Having data to manipulate on the page allows you to quickly see whether the code you’ve written is functioning as expected. It also allows you to format your html pages in a way that makes sense once real users are able to add their data and start using your app!

--

--

Melissa Gonzalez
Adventures in Code

Aspiring Web Developer. Fitness Enthusiast. Foodie. Beer Lover. Triathlete. Former Research Scientist.