< back to articles index

Split your Ruby on Rails seeds by environment

Published on 2 August 2023

Wait, what... why?

The seeds.rb file in Rails is a very convenient way to fill your database with false/test information during development. In building the application that powers this very blog I filled it with dozens of posts to help me style the pages while viewing actual (fake) content.

That is in Development though — as soon as you send it to Test, or Production you probably don't want that same content to appear in the database. Easy enough you might think... just do not seed the database in Production.

Well, yes, but with a small change in your code you can easily create separate seed files for each environment. Now you'll have the opportunity to write a separate seed for Development, creating hundreds of entries, and maybe something else — shorter typically — for Production.


Create a seeds folder

Inside your application's db/ folder, create a subfolder seeds.

mkdir db/seeds/ && cd db/seeds/

Create a seed file for each environment

Create a new (empty, for now) file for each environment in your new seeds/ folder.

touch development.rb test.rb production.rb

Set up seeds.rb to run the appropriate seed

Edit your main seeds.rb file to look as follows:

puts "Starting database seed."
puts "Current environment is: #{Rails.env.downcase}"
load(Rails.root.join('db', 'seeds', "#{Rails.env.downcase}.rb"))

# Do not add any seed command to this file. Instead, go to /db/seeds/ where you will find:
# development.rb
# production.rb
# test.rb
# Add your seed code into one of those depending on the environment where you wish for it to execute.

The third line (starting with load) will ensure that the appropriate seed file, from those three we created, gets executed wherever rails db:seed is run.

Now seed!

All that remains is for you to add your desired seed code to any one of the new seed files and it will execute in the appropriate environment. You'll probably want to start in development.rb and test it locally.

Rails templates

If you want the above to happen automatically when creating your new Rails application you might want to have a look at (and use, or copy) my Rails templates. Click here to view them on Github.