Is there a way to db:seed only one table in Rails?

Viewed 4163

I have a lot of data in my seeds, and have them separated into multiple files. I'm wondering if there is a way I can seed only one of these tables? In Laravel, I know it's possible to separate seeders into classes and then call:

php artisan db:seed --class CertainTableSeeder.

Is there a way to do this in Rails?

I have two files with a lot of seed data, joined through this function in seeds.rb

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

I've tried running commands like

rake db:seed SEED="CountriesTableSeeder.rb"

Only to find that this still reverts to running a normal db:seed, and my seeders are set up to destroy the table before each seed, but I'd rather not destroy the information from all tables each time I seed.

2 Answers

With below custom rake file, you can have multiple seed files in db/seeds/ folder.

# lib/tasks/custom_seed.rake
# 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)
      end
    end

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

  end
end

Then, in order to run specific seed file, you can just run

rake db:seed:seed_file_name

To run all the seeds file with order in that db/seeds folder, run below command

rake db:seed:all

To run only one seed file, perhaps in a folder, the following will do

bundle exec rails db:seed:folder_if_any:file_with_seed

So for your case, this would do

bundle exec rails db:seed:countries_table_seeder

PS: If you find that the command bundle exec rails doesn't work, use bundle exec rake instead

Related