Custom rake task for seeds
Closed this issue · 2 comments
I created this task for a project and I always use it, we could add it to the bootstrap:
# lib/tasks/custom_seeds.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) if File.exist?(filename)
end
end
end
end
Then you create a folder named db/seeds
and add as many files as you want there.
Then you just execute bundle exec rake db:seed:filename_without_rb_extension
@alebian Coool, what about the order of execution? there are a lot of seeds that depends of records that were created a few lines before. Maybe some order with timestamp/number like the ones the migrations uses?
@hdf1986 I don't think this is the use case (or I didn't understand you).
The approach I suggested is more for cases like filling e-commerce categories, and you probably want to do that in production too but you don't want to run the full seed in production so you just do bundle exec rake db:seed:categories
, If Categories needed something you can create them in that file. Also in the normal seed.rb you can add require_relative 'seeds/categories'