在 Rails 中从数据库重新生成 YAML 装置

Regenerate YAML Fixtures from DB in Rails

我正在使用 Rails,但我的 YAML 装置已损坏且无法使用。我想根据开发数据库重新生成 YAML fixtures。

不是试图获取所有的数据库数据并将其变成固定装置。我想要的是重新创建最初创建模型时创建的 standard fixtures。

在 Rails 4 中有没有简单的方法来做到这一点?

(我看到 this 页面讨论了如何 [我认为] 通过创建 rake 任务来做到这一点。但是 Q 是 3 年前的,我想知道是否已经创建了更直接的方法.)

没有标准或非常优雅的方式。

我在需要时使用此代码段:

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

我为此编写了 rake 任务。

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