-
-
Save jules2689/39e7f080f047b6e2c9f5cd149a909398 to your computer and use it in GitHub Desktop.
Rails 6: Dump Rails db to fixtures
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
# Original from http://snippets.dzone.com/posts/show/4468 by MichaelBoutros | |
# Forked from https://gist.github.com/ecleel/3dc89a753bac6a54bf8d170f63256f19 | |
# | |
# Optimized version which uses to_yaml for content creation and checks | |
# that models are ActiveRecord::Base models and not abstract class before trying to fetch | |
# them from database. | |
# | |
# Also supports nested resources and namespaces them correctly | |
# | |
# Tested in Rails 6.0.0 | |
# | |
namespace :db do | |
namespace :fixtures do | |
desc 'Dumps all models into fixtures.' | |
task :dump => :environment do | |
models_path = Pathname.new(Rails.root + 'app/models') | |
models = Dir.glob(Rails.root + 'app/models/**/*.rb').map do |model| | |
dir_and_name = Pathname.new(model).relative_path_from(models_path).to_s | |
dir_and_name.gsub(/\.rb$/,'').camelize | |
end | |
# include only ActiveRecord models and non-abstract class models | |
models.select! do |m| | |
m = m.constantize | |
m.ancestors.include?(ActiveRecord::Base) && !m.abstract_class | |
end | |
puts "Found models: #{models.to_sentence}" | |
puts "=> Dumping models:" | |
models.each do |m| | |
model = m.constantize | |
model_file = "#{Rails.root}/test/fixtures/#{m.underscore.pluralize}.yml" | |
puts " \x1b[94m#{m}\x1b[0m to \x1b[94m#{Pathname.new(model_file).relative_path_from(Rails.root)}\x1b[0m" | |
increment = 1 | |
entries = model.order(id: :asc).all | |
FileUtils.mkdir_p(File.dirname(model_file)) | |
File.open(model_file, 'w') do |f| | |
entries.each do |a| | |
attrs = a.attributes | |
attrs.delete_if { |_k, v| v.blank? } | |
output = { m + '_' + increment.to_s => attrs } | |
f << output.to_yaml.gsub(/^--- \n/,'') + "\n" | |
increment += 1 | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment