Ruby-on-rails 将数据库表导出到 YAML 文件的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/490507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:56:03  来源:igfitidea点击:

Best way to export a database table to a YAML file?

ruby-on-railsyaml

提问by Mattew

I have some data in my development database that I would like to utilize as fixtures in my test environment. What is the best way in Rails 2.x to export a database table to a YAML fixture?

我的开发数据库中有一些数据,我想将它们用作测试环境中的夹具。Rails 2.x 中将数据库表导出到 YAML 设备的最佳方式是什么?

采纳答案by Andrew Vit

There is a rake task for this. You can specify RAILS_ENV if needed; the default is the development environment:

为此有一个耙子任务。如果需要,您可以指定 RAILS_ENV;默认是开发环境:

rake db:fixtures:dump
    # Create YAML test fixtures from data in an existing database.

回答by Geekygecko

I have been using YamlDb to save the state of my database.

我一直在使用 YamlDb 来保存我的数据库状态。

Install it with the following command:

使用以下命令安装它:

script/plugin install git://github.com/adamwiggins/yaml_db.git 

Use the rake task to dump the contents of Rails database to db/data.yml

使用 rake 任务将 Rails 数据库的内容转储到 db/data.yml

rake db:data:dump

Use the rake task to load the contents of db/data.yml into the database

使用 rake 任务将 db/data.yml 的内容加载到数据库中

rake db:data:load

This is the creators homepage:

这是创作者主页:

http://blog.heroku.com/archives/2007/11/23/yamldb_for_databaseindependent_data_dumps/

http://blog.heroku.com/archives/2007/11/23/yamldb_for_databaseindependent_data_dumps/

回答by Brian Armstrong

This plugin will add the functionality you want. It was extracted from ActiveRecord so no longer comes by default.

此插件将添加您想要的功能。它是从 ActiveRecord 中提取的,因此默认情况下不再出现。

script/plugin install http://github.com/topfunky/ar_fixtures

script/plugin install http://github.com/topfunky/ar_fixtures

Then run:

然后运行:

rake db:fixtures:dump MODEL=ModelName

rake db:fixtures:dump MODEL=ModelName

回答by jpgeek

For Rails 3, if you want to dump yaml from the DB and use it as a fixture, I use this code:

对于 Rails 3,如果您想从数据库中转储 yaml 并将其用作夹具,我使用以下代码:

module DbToFixture

  TEMP_FIXTURE_PATH = Rails.root.join("test", "new_fixtures")

  def fixturize(model)
    Dir.mkdir(TEMP_FIXTURE_PATH) unless File.exists?(TEMP_FIXTURE_PATH)
    fname = model.table_name
    file_path = TEMP_FIXTURE_PATH.join(fname)
    File.open(file_path, 'w') do |f|
      model.all.each do |m|
        f.write(m.to_yaml)
      end
    end
  end

end

I just run it from the console with

我只是从控制台运行它

require './lib/db_to_fixture'
include DbToFixture
fixturize ModelName

I have not been able to get ar_fixtures to work with Rails 3 (haven't tried very hard though). Yaml db is great for dumping and saving the db, but its format is not compatible with fixtures.

我一直无法让 ar_fixtures 与 Rails 3 一起工作(虽然还没有很努力)。Yaml db 非常适合转储和保存 db,但其格式与夹具不兼容。

回答by Joe Goggins

Iron Fixture Extractorwas built for exactly this purpose. It's particularly good for situations where you want to use different fixture sets for different testing scenarios (rather than having all fixtures for all tests). It provides functionality for extracting, loading, rebuilding fixtures, truncating tables, or snagging particular hashes from your fixture yaml files.

Iron Fixture Extractor正是为此目的而制造的。它特别适用于您想为不同的测试场景使用不同的夹具集(而不是为所有测试使用所有夹具)的情况。它提供了提取、加载、重建夹具、截断表或从您的夹具 yaml 文件中获取特定哈希的功能。

回答by vanboom

Very simple gem will create yaml fixtures from existing database...

非常简单的 gem 将从现有的数据库创建 yaml 固定装置......

github.com/vanboom/yaml_dump

github.com/vanboom/yaml_dump

Works with Rails 4.

适用于 Rails 4。

回答by Zoli

rake db:fixtures:dump

rake db:fixtures:dump

has been changed to

已更改为

rake db:extract_fixtures

rake db:extract_fixtures

回答by Pierre

Here's a rake task that will do exactly that (tested in Rails 3.2.8):

这是一个 rake 任务,它可以做到这一点(在 Rails 3.2.8 中测试过):

namespace :db do
    task :extract_fixtures => :environment do
      sql  = 'SELECT * FROM "%s"'
      skip_tables = ["schema_migrations"]
      ActiveRecord::Base.establish_connection
      if (not ENV['TABLES'])
        tables = ActiveRecord::Base.connection.tables - skip_tables
      else
        tables = ENV['TABLES'].split(/, */)
      end
      if (not ENV['OUTPUT_DIR'])
        output_dir="#{Rails.root}/test/fixtures"
      else
        output_dir = ENV['OUTPUT_DIR'].sub(/\/$/, '')
      end
      (tables).each do |table_name|
        i = "000"
        File.open("#{output_dir}/#{table_name}.yml", 'w') do |file|
          data = ActiveRecord::Base.connection.select_all(sql % table_name.upcase)
          file.write data.inject({}) { |hash, record|
            hash["#{table_name}_#{i.succ!}"] = record
            hash
          }.to_yaml
          puts "wrote #{table_name} to #{output_dir}/"
        end
      end
    end
end

Source: http://sachachua.com/blog/2011/05/rails-exporting-data-specific-tables-fixtures/

资料来源:http: //sachachua.com/blog/2011/05/rails-exporting-data-specific-tables-fixtures/

Note: I had to make a few changes to the blog code to make it more cross-database compatible and work in Rails 3.2

注意:我必须对博客代码进行一些更改,以使其跨数据库兼容并在 Rails 3.2 中工作

回答by Tom Maeckelberghe

 > rails c
 irb> puts Modelname.all.to_yaml

then copy & paste it in file and edit it to match what fixtures expect.

然后将其复制并粘贴到文件中并对其进行编辑以匹配灯具的预期。

It's manual labor but if you need this just once probably the fastest way.

这是体力劳动,但如果您只需要一次,这可能是最快的方法。

回答by Hari Karam Singh

For dumping for rspec/cucumber test fixtures in Rails 3 this is the best answer I've found: What is the standard way to dump db to yml fixtures in rails?

对于在 Rails 3 中转储 rspec/cucumber 测试装置,这是我找到的最佳答案: 将 db 转储到 Rails 中的 yml 装置的标准方法是什么?