Skip to content

Instantly share code, notes, and snippets.

@iiska
Created December 28, 2011 13:17
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save iiska/1527911 to your computer and use it in GitHub Desktop.
Save iiska/1527911 to your computer and use it in GitHub Desktop.
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
puts "Found models: " + models.join(', ')
models.each do |m|
model = m.constantize
next unless model.ancestors.include?(ActiveRecord::Base)
puts "Dumping model: " + m
entries = model.find(:all, :order => 'id ASC')
increment = 1
model_file = RAILS_ROOT + '/test/fixtures/' + m.underscore.pluralize + '.yml'
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
@thams
Copy link

thams commented Oct 30, 2013

FWIW, turned this into a gem, (and fixed some things for newer Rails versions). https://github.com/thams/db_fixtures_dump

@tssm
Copy link

tssm commented Jun 9, 2016

@thams 👍 ❤️ 🎉 🎈

@kuboon
Copy link

kuboon commented May 12, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment