Rails Multiple Seed Files

If you have a larger Rails project or one with many resources, managing a single database seed file can get out of hand. In the name of DRY-ing out code, this article walks you through how to abstract your seed data into multiple files.

So, the approach is to create a new directory: db/seeds, and had your seed files in this location. I think the best approach is to separate your concerns across your seed files. Create multiple seed files to manage each resource more easily and place them in this new directory.

When you execute rails db:migrate, Rails will only run the file: db/seeds.rb. To fix this, we will use Ruby to parse the new directory for files. So, in the default db/seeds.rb file add the following:

Dir[File.join(Rails.root, "db", "seeds", "*.rb")].sort.each do |seed|

puts "seeding - #{seed}. loading seeds, for real!"

load seed
end

Now, when you run the seed command, it will parse all of your files and print to the command line exactly which file is being loaded.