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

发布于 2024-07-12 08:49:47 字数 79 浏览 10 评论 0原文

我的开发数据库中有一些数据,我想将它们用作测试环境中的固定装置。 Rails 2.x 中将数据库表导出到 YAML 固定装置的最佳方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

勿忘初心 2024-07-19 08:49:47

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

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

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

rake db:fixtures:dump
    # Create YAML test fixtures from data in an existing database.
诗化ㄋ丶相逢 2024-07-19 08:49:47

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

使用以下命令安装它:

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

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

rake db:data:dump

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

rake db:data:load

这是创建者主页:

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

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

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 db:data:dump

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

rake db:data:load

This is the creators homepage:

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

十级心震 2024-07-19 08:49:47

该插件将添加您想要的功能。 它是从 ActiveRecord 中提取的,因此不再默认提供。

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

然后运行:

rake db:fixtures:dump MODEL=ModelName

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

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

Then run:

rake db:fixtures:dump MODEL=ModelName

蓝眸 2024-07-19 08:49:47

对于 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

我只是从控制台运行它,但

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

我无法让 ar_fixtures 与 Rails 3 一起使用(还没有虽然很努力)。 Yaml 数据库非常适合转储和保存数据库,但其格式与固定装置不兼容。

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

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.

萤火眠眠 2024-07-19 08:49:47

铁夹具提取器正是为此目的而构建的。 它特别适合您想要对不同测试场景使用不同夹具集(而不是为所有测试使用所有夹具)的情况。 它提供了提取、加载、重建固定装置、截断表或从固定装置 yaml 文件中获取特定哈希值的功能。

Iron Fixture Extractor was 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.

猥︴琐丶欲为 2024-07-19 08:49:47

rake db:fixtures:dump

已更改为

rake db:extract_fixtures

rake db:fixtures:dump

has been changed to

rake db:extract_fixtures

转瞬即逝 2024-07-19 08:49:47
 > rails c
 irb> puts Modelname.all.to_yaml

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

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

 > 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.

屌丝范 2024-07-19 08:49:47

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

github.com/vanboom/yaml_dump

与 Rails 一起使用4.

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

github.com/vanboom/yaml_dump

Works with Rails 4.

假装不在乎 2024-07-19 08:49:47

这里有一个 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

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

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

Here's a rake task that will do exactly that (tested in 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/

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

晌融 2024-07-19 08:49:47

我在 Rails 6 中使用了这个:

# How to run:
# rake fixtures:import_db_table[my_table]
namespace :fixtures do
  desc 'Convert development table into Rails test fixtures'
  task :import_db_table, [:table_name] => :environment do |_task, args|
    begin
      table_name = args[:table_name]
      raise "Missing table name" if table_name.blank?
      conter = '000'
      file_path = "#{Rails.root}/spec/fixtures/#{table_name}.yml"
      ActiveRecord::Base.establish_connection
      File.open(file_path, 'w') do |file|
        rows = ActiveRecord::Base.connection.select_all("SELECT * FROM #{table_name}")
        data = rows.each_with_object({}) do |record, hash|
          suffix = record['id'].blank? ? conter.succ! : record['id']
          hash["#{table_name.singularize}_#{suffix}"] = record
        end
        puts "Writing table '#{table_name}' to '#{file_path}'"
        file.write(data.to_yaml)
      end
    ensure
      ActiveRecord::Base.connection.close if ActiveRecord::Base.connection
    end
  end
end

提取自 此处(导入所有表)。

I used this in Rails 6:

# How to run:
# rake fixtures:import_db_table[my_table]
namespace :fixtures do
  desc 'Convert development table into Rails test fixtures'
  task :import_db_table, [:table_name] => :environment do |_task, args|
    begin
      table_name = args[:table_name]
      raise "Missing table name" if table_name.blank?
      conter = '000'
      file_path = "#{Rails.root}/spec/fixtures/#{table_name}.yml"
      ActiveRecord::Base.establish_connection
      File.open(file_path, 'w') do |file|
        rows = ActiveRecord::Base.connection.select_all("SELECT * FROM #{table_name}")
        data = rows.each_with_object({}) do |record, hash|
          suffix = record['id'].blank? ? conter.succ! : record['id']
          hash["#{table_name.singularize}_#{suffix}"] = record
        end
        puts "Writing table '#{table_name}' to '#{file_path}'"
        file.write(data.to_yaml)
      end
    ensure
      ActiveRecord::Base.connection.close if ActiveRecord::Base.connection
    end
  end
end

Extracted from here (which imports all tables).

故事和酒 2024-07-19 08:49:47

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

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文