Most applications I’ve worked on required some kind of seed data. For example, I’ve used seed data to create a super admin user so the site can actually be used upon a fresh install. Some other common cases include things like, list of credit card types, names of countries/states etc. This post is about some ideas to manage thsese seed data in a Ruby on Rails project.
Where to put the seed data?
I think you have 2 choices to pick from.
I prefer having it in the seeds.rb whenever possible since this is the obvious place for it. But I’ve often put them in migrations as well. There are trade-offs associated with both.
Migrations only run once. This means, “double/miltiple seeding” is not a concern at all. So, you can write a migration with some seeding command as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
This works great. It creates the super user and by virtue of migrations, it only ever creates one super admin.
The caveat with this approach is, if you change certain things later, then this migration will fail to run. For example, say we added a required field to user as follows:
1 2 3
Now, if you run the migration on a freshly checked out code, it will fail due to this validation. One workaround is to fix the code in this migration. But for people that already ran the migrations, and likely your production environment already did so, this has no effect. At this point, it starts getting complicated and some band-aid solutions are usually implemented.
On the other hand, if you are using db/seeds.rb for seed data, you’d have to make sure its idempotent. So, a rerun should not create a 2nd copy of the objects. As a start, your code could be like this:
1 2 3
With this in place, you can easily incorporate the change for the new validation as follows:
1 2 3 4 5 6
This would work for people who already had a super user and also for people that just got a fresh copy of the code.
So, I prefer putting data in seeds.rb with idempotency.
In addition to handling such cases, it also makes it easy for anyone to take glance at the seed data in one place.
How to handle large amount of seed data?
When you have more than a handful of data to seed, I’d recommend tidying up your db/seeds.rb into a more manageable structure. Here’s how I’d do it:
1 2 3 4 5 6
With this structure in place, you can turn you seeds.rb into a simple manifesto file as follows:
This will help you keeping things organized and hopefully give you a happier solution to the seed data problem.