Skip to content

Instantly share code, notes, and snippets.

@troelskn
Forked from ecleel/db_fixtures_dump.rake
Last active January 21, 2024 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troelskn/4dbf00233be0ef21e336b5f05cda891c to your computer and use it in GitHub Desktop.
Save troelskn/4dbf00233be0ef21e336b5f05cda891c to your computer and use it in GitHub Desktop.
Rails 5: Dump Rails db to fixtures
# Original from http://snippets.dzone.com/posts/show/4468 by MichaelBoutros
#
# Optimized version which uses to_yaml for content creation and checks
# that models are ActiveRecord::Base models before trying to fetch
# them from database.
namespace :db do
namespace :fixtures do
desc 'Dumps all models into fixtures.'
task dump: :environment do
models = Dir.glob(Rails.root + 'app/models/**.rb').map do |s|
Pathname.new(s).basename.to_s.gsub(/\.rb$/,'').camelize
end
# excludes models
excludes = %w(ApplicationRecord)
puts "Found models: " + models.join(', ')
models.reject { |m| m.in?(excludes) }.each do |m|
model = m.constantize
next unless model.ancestors.include?(ActiveRecord::Base)
puts "Dumping model: " + m
entries = model.order(id: :asc).all
model_file = "#{Rails.root}/test/fixtures/#{m.underscore.pluralize}.yml"
File.open(model_file, 'w') do |f|
entries.each do |a|
attrs = {}
a.attributes.each do |k, v|
next if v.blank?
mm = k.match(/^(.*)_id$/)
if mm
attrs[mm[1]] = "#{mm[1]}_#{v}"
elsif v.kind_of?(ActiveSupport::TimeWithZone)
attrs[k] = v.to_s
else
attrs[k] = v
end
end
key = m.underscore + '_' + attrs["id"].to_s
attrs.delete("id")
output = { key => attrs }
f << output.to_yaml.gsub(/^--- \n/,'') + "\n"
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment