We need to add more seed data for some newly added tables to "version 100" of our rails project.
However, if we simply add it to the seeds.rb and re-run the rake db:seed command, it will of course RE-add the original seed data, duplicating it.
So if you've already added seed data to seeds.rb for, say, TableOne ... how can we incrementally add seed data for TableTwo and TableThree at later stages of development?
I'd hoped I could simply create a NEW seeds_two.rb file and run rake db:seeds_two
but that gave an error Don't know how to build task 'db:seeds_two'
So it looks like ONLY "seeds.rb" can be used - so how DO people maintain incremental additions to seed data?
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.
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.
You can re-use the seed
task, but make it idempotent.
To make the seed idempotent, simply check for the existence of the condition before executing a command. An example: do you want to create a new admin user?
User.find_or_create_by_username(:username => "admin")
instead of
User.create(:username => "admin")
However, seed
should be used to populate your database when the project is created. If you want to perform complex data seeding durin the lifecycle of the app, simply create a new rake task, execute it then remove it.
For those who have concerns about this question
We can have multiple seed files in db/seeds/
folder, and, we can write a rake task to run separate file as we desire to run
# 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