in Programming, Tips, Uncategorized

Easily create database records with db:seed

I have a project and a task model. Projects has many tasks. I can easily create many records of these in the database using the db/seed.rb file. In this file you can write many ActiveRecord commands to be executed when you run rake db:seed Example where the seed.rb contains

Project.create!(name: 'Project')
Project.create!(name: 'Project1')

This is will create and save two records into the database when you run rake db:seed

If you wanted to create many projects and tasks, then you would not want to be defining each record like what I had above. Instead you would want to dynamically generate as many projects and tasks as you want. The way I did it was through looping through a range in order to assign a number to the project and task attributes.

project_array = []                                                         
(1..4).each do |num|                                                       
  project_array <<  Project.create!(name: "Project#{num}")                 

project_array.each do |project|                                            
  (1..20).each do |num|                                                    
    Task.create!(description: "Task#{num}", project_id:        

We first define the project_array to store all the created projects. We have a range passed into a block in order to generate the dynamically named project name. The project_array is then appended with Project objects.

The second loop first loops through all the projects then a range. The project loop comes first because you want to have many tasks under a few projects. In this case we are creating 20 tasks with the project_id attribute set to the

This can be refactored and extended further, but for such a simple goal, no need to give it too much thought.

Rake db:reset

If you happen need to reset the database, then you do not need to run rake db:seed afterwards. rake db:reset performs the dropping, migrating, and seeding of the tables for you.

Write a Comment



  • Railscast 032 Time in Text Field | Patrick Perey

    […] you need to do the same thing on. I have used metaprogramming when I made a seed.rb file to fill up the database with records. These methods saves a lot of time if made […]

  • Railscast 023 Counter Cache Column | Patrick Perey

    […] populated the database using the seed.rb. Instead of declaring each record one by one, I did it dynamically with ruby. More in the blog […]