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.
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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With