31

開発データベースに、テスト環境のフィクスチャとして利用したいデータがいくつかあります。Rails 2.xでデータベーステーブルをYAMLフィクスチャにエクスポートするための最良の方法は何ですか?

4

11 に答える 11

24

これには rake タスクがあります。必要に応じて RAILS_ENV を指定できます。デフォルトは開発環境です。

rake db:fixtures:dump
    # Create YAML test fixtures from data in an existing database.
于 2009-02-05T02:39:54.950 に答える
21

データベースの状態を保存するために 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/

于 2009-01-29T04:59:12.747 に答える
9

このプラグインはあなたが望む機能を追加します。ActiveRecordから抽出されたため、デフォルトでは提供されなくなりました。

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

次に、以下を実行します。

rake db:fixtures:dump MODEL=ModelName

于 2010-04-16T05:45:07.353 に答える
6

Rails 3の場合、DBから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をRails3で動作させることができませんでした(ただし、あまり頑張っていません)。Yaml dbは、dbのダンプと保存に最適ですが、その形式はフィクスチャと互換性がありません。

于 2012-09-03T05:24:17.850 に答える
2

非常に単純な gem は、既存のデータベースから yaml フィクスチャを作成します...

github.com/vanboom/yaml_dump

Rails 4 で動作します。

于 2014-02-19T17:22:40.703 に答える
2

rake db:fixtures:dump

に変更されました

rake db:extract_fixtures

于 2010-04-07T14:48:20.353 に答える
1

これを正確に実行する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/

注:ブログコードにいくつかの変更を加えて、データベース間の互換性を高め、Rails3.2で機能させる必要がありました。

于 2012-10-11T18:47:49.320 に答える
0

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

ここから抽出されます(すべてのテーブルをインポートします)。

于 2020-06-24T11:42:57.697 に答える
0

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?

于 2013-04-04T11:34:49.613 に答える