Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Generate fixtures from db. Readable by rake db:fixtures:load
# lib/tasks/db_fixtures_export.rake
namespace 'db:fixtures' do
desc "generate fixtures from the current database"
task :export => :environment do
models = defined?(AppicationRecord) ? ApplicationRecord.decendants : ActiveRecord::Base.descendants
models.each do |model|
puts "exporting: #{model}"
# Hoge::Fuga -> test/fixtures/hoge/fuga.yml
filepath = Rails.root.join('test/fixtures', "#{}.yml")
FileUtils.mkdir_p filepath.dirname'w') do |file|
hash = {}
model.find_each do |r|
key = r.try(:name) || "#{filepath.basename('.*')}_#{}"
hash[key] = r.attributes.except(:password_digest)
file.write hash.to_yaml
Copy link

NorseGaud commented Jun 11, 2017

I had to next if == "ApplicationRecord" AND next if == "ActiveRecord::SessionStore::Session" right below the puts for model or else it was not functioning properly.

Copy link

I also had to fix the pluralize thing:

model_name =
model_name = model_name.pluralize if model.pluralize_table_names?
model_name = model_name.underscore

filepath = Rails.root.join('test/fixtures', "#{model_name}.yml")

Copy link

There are two spelling errors on Line 7, it should be

        models = defined?(ApplicationRecord) ? ApplicationRecord.descendants : ActiveRecord::Base.descendants

Copy link

Thanks for updating this to Rails 5! Here's a fork that fixes the spelling errors:

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