Create and run separated seed files

Usually We use the great power of rails db:seed in any Rails project. The seeds file provides us a way to quickly manipulate our sample and necessary data, especially at the beginning of our project.

But when times gone, we see that we often add more and more data to our seeds file and we need to rerun the command again. So, we need to comment out the old code in seeds file, or, we need to strictly validate the models. We absolutely don’t want our seed data as a mess

That’s why I start investigating the way to separate our seeds into different files, so we can choose whichever seed file we want to run, to void duplication or commenting old code. But we need a way for other programmer who joins our project later to run all of the files.

Let’s move on.

Just create a rake tasks to handle it. First, create a file called custom_seed.rake in lib/tasks/ folder

namespace :db do
  namespace :seeds do

    Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')].each do |filename|
      task_name = File.basename(filename, '.rb').intern

      task task_name => :environment do
        load(filename)
      end
    end

    task :all => :environment do
      Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')].sort.each do |filename|
        load(filename)
      end
    end

  end
end

The above code will generate rails db:seeds:seed_file_name command and rails db:seeds:all command.

Now, you just need to create db/seeds folder and then create ruby files to generate seed data for your project like user.rb , product.rb etc …

You can read this StackOverflow link also

Published by

Colin Dao

I am a hardworking Rubyist in Hanoi, Vietnam

Leave a comment