【问题标题】:Best way to export a database table to a YAML file?将数据库表导出到 YAML 文件的最佳方法?
【发布时间】:2010-10-04 04:19:54
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails yaml


    【解决方案1】:

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

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

    【讨论】:

    • db:fixtures:dump on Rails?我在 2.3.5 上看不到。
    • 看起来像是从 ActiveRecord 中提取的。您可以使用此插件将其添加回来:github.com/topfunky/ar_fixtures 然后运行:rake db:fixtures:dump MODEL=ModelName
    • 这仅对 Rails 3 有效。
    • 'rake db:fixtures:dump' 是否以任何方式影响当前数据库?还是只导出到 YAML?
    【解决方案2】:

    我一直在使用 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/

    【讨论】:

    • 如何以表为目标进行转储,而不是转储整个数据库?
    【解决方案3】:

    这个插件会添加你想要的功能。它是从 ActiveRecord 中提取的,因此默认情况下不再提供。

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

    然后运行:

    rake db:fixtures:dump MODEL=ModelName

    【讨论】:

      【解决方案4】:

      对于 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 db 非常适合转储和保存 db,但它的格式与夹具不兼容。

      【讨论】:

      • 我是否将文件命名为 db_to_fixture?令人惊奇的是,Rails 在最新的 Rails 中没有简单的单行命令可做。这是我需要经常做的事情。
      • 太棒了。无论如何,是的,它必须是调用模块的蛇形案例。
      【解决方案5】:

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

      【讨论】:

      • 感谢您的推荐。我发现它特别有用,因为它允许我在一个相当大的表上提取一部分数据用于测试目的。
      【解决方案6】:

      rake db:fixtures:dump

      已改为

      rake db:extract_fixtures

      【讨论】:

      • 适用于哪个版本的导轨?对于被问到的 2.x,这似乎不是真的。也许您的答案是特定于 rails 3.x 的?
      • 原版 Rails 3.x 中也没有。
      • 不起作用。您是否正在使用一些添加此功能的库?
      【解决方案7】:

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

      github.com/vanboom/yaml_dump

      适用于 Rails 4。

      【讨论】:

        【解决方案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
        

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

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

        【讨论】:

        • 不错的脚本。我必须删除“.upcase”才能使其在 Rails 4 中工作,但除此之外,它可以像宣传的那样工作。谢谢。
        【解决方案9】:
         > rails c
         irb> puts Modelname.all.to_yaml
        

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

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

        【讨论】:

          【解决方案10】:

          对于在 Rails 3 中转储 rspec/cucumber 测试装置,这是我找到的最佳答案: What is the standard way to dump db to yml fixtures in rails?

          【讨论】:

            【解决方案11】:

            我在 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
            

            here(导入所有表)中提取。

            【讨论】:

              猜你喜欢
              • 2011-10-09
              • 2016-01-15
              • 2012-05-22
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多