Last active
March 4, 2023 00:11
-
-
Save DevGW/34ed93d3104856bc25ef5d44ab31b41b to your computer and use it in GitHub Desktop.
Generate seed.rb from existing models and data #ruby #RoR #hha_ank
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
namespace :db do | |
desc "Generate a seed.rb file with all records from all models" | |
task :generate_seed_file => :environment do | |
#start timer | |
time = Benchmark.realtime do | |
seed_file = File.open("#{Rails.root}/tmp/seeds.rb", "w") | |
# eager load to get all models | |
Rails.application.eager_load! | |
# Get all ActiveRecord models except for those in Rails internal namespaces | |
models = ApplicationRecord.descendants.reject { |model| model.name =~ /^Rails/ } | |
puts "Discovered #{models.count} models" | |
models.each do |model| | |
# Write the model name to the seed file | |
seed_file.write("# #{model.name}\n") | |
# Write each record to the seed file | |
puts "Processing #{model.name}..." | |
puts "Extracting data from #{model.all.count} records" | |
puts "Extracting #{model.first.attributes.count} attributes from each record" | |
model.all.each do |record| | |
seed_file.write("#{model.name}.create(#{record.attributes.except("id", "created_at", "updated_at").to_s.gsub(/\=>/, ': ')})\n") | |
end | |
# Add a blank line between models | |
seed_file.write("\n") | |
end | |
seed_file.close | |
end | |
puts "Seed file generated successfully at tmp/seeds.rb in #{time.round(2)} seconds." | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment