【问题标题】:Regenerate YAML Fixtures from DB in Rails在 Rails 中从 DB 重新生成 YAML 夹具
【发布时间】:2015-08-20 20:40:24
【问题描述】:

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

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

在 Rails 4 中是否有一种简单的方法可以做到这一点?

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

【问题讨论】:

  • 我认为您应该尝试使用您链接的答案。我真的怀疑有没有更好的方法来做你所要求的。这不是一个正常的用例。
  • 尝试……但失败了。 :/ 我正在查看create_fixtures(),但由于缺少文档而无法弄清楚如何使用它...

标签: ruby-on-rails ruby yaml fixture


【解决方案1】:

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

我在需要时使用这个 sn-p:

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

【讨论】:

  • 这是一个非常有用的答案! (链接到的答案对我来说不能正常工作)
【解决方案2】:

我为此编写了 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

【讨论】:

    猜你喜欢
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2017-10-25
    • 2020-09-07
    相关资源
    最近更新 更多