Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regenerate YAML Fixtures from DB in Rails

I am using Rails and my YAML fixtures are corrupted and unusable. I would like to regenerate the YAML fixtures based on the development database.

I am not trying to take all the DB data and turn it into a fixture. What I want is to recreate the standard fixtures that were created initially when the models were first created.

Is there an easy way to do this in Rails 4?

(I saw this page that discusses how to do this [I think] by creating a rake task. However the Q is from 3 years ago and I wonder if a more direct method has been created yet.)

like image 670
Jo.P Avatar asked Dec 14 '22 12:12

Jo.P


2 Answers

There is no standard or very elegant way.

I use this snippet when I need to:

File.open("#{Rails.root}/spec/fixtures/users.yml", 'w') do |file|
  data = User.all.to_a.map(&:attributes)
  data.each{|x| x.delete('id')}
  file.write data.to_yaml
end
like image 83
EugZol Avatar answered Dec 30 '22 21:12

EugZol


I wrote rake task for this.

https://gist.github.com/kuboon/55d4d8e862362d30456e7aa7cd6c9cf5

# 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
like image 37
kuboon Avatar answered Dec 30 '22 21:12

kuboon