Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 210
JoeyMousepad Avatar asked Jun 08 '19 19:06

JoeyMousepad


People also ask

How do I run a specific seed in rails?

To run the default seeds. rb file, you run the command rake db:seed . If I create a file in the db directory called seeds_feature_x. rb , what would the rake command look like to run (only) that file?

What is DB seed in rails?

Rails seed files are a useful way of populating a database with the initial data needed for a Rails project. The Rails db/seeds. rb file contains plain Ruby code and can be run with the Rails-default rails db:seed task.

What is Seeds rb?

The seeds.rb file is where the seed data is stored, but you need to run the appropriate rake task to actually use the seed data. Using rake -T in your project directory shows information about following tasks: rake db:seed. Load the seed data from db/seeds.rb. rake db:setup.


1 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
like image 164
quyetdc Avatar answered Sep 19 '22 16:09

quyetdc