Monthly Archives: September 2016

Custom seed files in Ruby on Rails 5 project

For project purpose sometimes we need to create multiple seed files. We can do this by simple creating rake tasks in ruby on rails.

To create a rake task for multiple seed file you can use below code:

# lib/tasks/custom_seed.rake
namespace :db do
  namespace :seed 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) if File.exist?(filename)
      end
    end
  end
end

Please save this code to lib/tasks/custom_seed.rake file

Now create a folder called seeds inside your db folder: db/seeds

Now you can run any seed file from this folder by simple running below command:

# Name of the file without the .rb extension 
rake db:seed:seed_file_name 

Happy Coding 🙂