Skip to content

Instantly share code, notes, and snippets.

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 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|\.rb$/,'').camelize
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', '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
Copy link

thams commented Oct 30, 2013

FWIW, turned this into a gem, (and fixed some things for newer Rails versions).

Copy link

tssm commented Jun 9, 2016

@thams 👍 ❤️ 🎉 🎈

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