Rails 6 — Custom Seed Files

Zachary Weiner
2 min readFeb 17, 2020

--

While building applications in Rails it’s very common to have to add a new model after you’ve already set up a DB and added some seed data. So, what do you do when you need to inject data into the new model, but dont want to drop the whole data base?

Well, you can jump in the rails console and enter the new records by hand. You can build a scaffold for the model and enter the data through the webpage. But, both of those options have 2 main flaws:

1- It’s time consuming and error prone.
2- You’ll have to do it all again if fo rsome reason you end up dropping the DB.

So what’s a better solution?

A Custom Rake Task & Custom Seed Files

When we run commands like

rake db:seed 

Our Rails App knows exactly what to do because there is a file that recieves this command line instruction and executes the migration script. The file looks for our db/seeds.rake file, and runs all the Ruby written inside of it.

To get new data into the DB without creating new records, we could chose to write an Upsert from the default seed file, but that can get messy and isn’t availble in Rails version that came before 6.

The Rails way to get ‘r done is to make our own custom seed files, and a simple rake task that can handle a similar command from the command line.

First, lets make the custom Rake File. The new Rake File should live in the folder tasks folder and lets name it custom_seed.rake

lib/tasks/custom_seed.rake 

Then inside the file just copy and paste the following code

namespace :db do
namespace :seed do
Dir[Rails.root.join('db', 'seeds', '*.rb')].each do |filename|
task_name = File.basename(filename, '.rb')
desc "Seed " + task_name + ", based on the file with the same name in `db/seeds/*.rb`"
task task_name.to_sym => :environment do
load(filename) if File.exist?(filename)
end
end
end
end

This routine will look at the db folder, look for a seeds folder and then search the seeds folder for a file that matches the name we type after

rake db:seed: 

So for example if we wanted to make a custom seed file for an object named Posts ->

We would add a file named posts.rake to the folder db/seeds/

db/seeds/posts.rake 

Your posts.rake file can run all the inserts for the Posts you would like to include in your DB set up.

Post.create!(title: 'My Awesome Post', meta: 'Awesome Stuff', ....)

Now, all we need to do to get the new objects into the Posts Table in our DB without runing the rest of the data is

rake db:migrate:posts

And BOOM! You’re up and running with a few posts, and you’ll never have to type them in again 😆.

--

--

Zachary Weiner

Founder @MagicDapp.io & @AlphaDapp.com | Find @DevelopingZack on Twitter & Telegram