Skip to content

Instantly share code, notes, and snippets.

Forked from iiska/db_fixtures_dump.rake
Last active January 21, 2024 10:25
  • Star 16 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ecleel/3dc89a753bac6a54bf8d170f63256f19 to your computer and use it in GitHub Desktop.
Rails 5: 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
# excludes models
excludes = %w(ApplicationRecord)
puts "Found models: " + models.join(', ')
models.reject{|m|}.each do |m|
model = m.constantize
next unless model.ancestors.include?(ActiveRecord::Base)
puts "Dumping model: " + m
entries = model.order(id: :asc).all
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment