Is there any way to have multiple seeds.rb files? Any kind of 'versioning' for seed data?
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