Created
May 12, 2017 15:58
-
-
Save kuboon/55d4d8e862362d30456e7aa7cd6c9cf5 to your computer and use it in GitHub Desktop.
Generate fixtures from db. Readable by rake db:fixtures:load
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# lib/tasks/db_fixtures_export.rake | |
namespace 'db:fixtures' do | |
desc "generate fixtures from the current database" | |
task :export => :environment do | |
Rails.application.eager_load! | |
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', "#{model.name.underscore}.yml") | |
FileUtils.mkdir_p filepath.dirname | |
filepath.open('w') do |file| | |
hash = {} | |
model.find_each do |r| | |
key = r.try(:name) || "#{filepath.basename('.*')}_#{r.id}" | |
hash[key] = r.attributes.except(:password_digest) | |
end | |
file.write hash.to_yaml | |
end | |
end | |
end | |
end |
I also had to fix the pluralize thing:
model_name = 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")
There are two spelling errors on Line 7, it should be
models = defined?(ApplicationRecord) ? ApplicationRecord.descendants : ActiveRecord::Base.descendants
Thanks for updating this to Rails 5! Here's a fork that fixes the spelling errors: https://gist.github.com/existentialmutt/a36d024b0ca7bbf5d3e81fa8b2cd692d
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had to
next if model.name == "ApplicationRecord"
ANDnext if model.name == "ActiveRecord::SessionStore::Session"
right below the puts for model or else it was not functioning properly.