3

由于一些非标准的表创建选项,我被迫使用 sql 转储而不是标准的 schema.rb(即我在 environment.rb 中取消了这一行的注释config.active_record.schema_format = :sql)。我注意到,当我使用 sql 转储时,我的装置似乎没有加载到数据库中。一些数据已加载到其中,但我不确定它来自哪里。这是正常的吗?如果这是正常的,谁能告诉我这些其他数据来自哪里?

4

2 回答 2

1

这是一个非常古老的问题,但即使在将近 10 年后,答案仍然是一样的 - 似乎固定装置忽略了模式格式并且被硬编码以查找 YAML 文件。这是 Rails 5.2-stable 的 Rake 任务:

https://github.com/rails/rails/blob/5-2-stable/activerecord/lib/active_record/railties/databases.rake#L198

第 214 行用于Dir["#{fixtures_dir}/**/*.yml"]查找文件,因此只会.yml读取。

解决方案围绕着将您的 SQL 固定装置加载到原本为空的数据库中,然后使用yaml_db gem或类似本博客文章中描述的内容将它们转储为 YAML 。由于指向博客文章的链接通常很快就会消失,因此我复制了以下来源:

namespace :db do
  desc 'Convert development DB to Rails test fixtures'
  task to_fixtures: :environment do
    TABLES_TO_SKIP = %w[ar_internal_metadata delayed_jobs schema_info schema_migrations].freeze

    begin
      ActiveRecord::Base.establish_connection
      ActiveRecord::Base.connection.tables.each do |table_name|
        next if TABLES_TO_SKIP.include?(table_name)

        conter = '000'
        file_path = "#{Rails.root}/test/fixtures/#{table_name}.yml"
        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
      end
    ensure
      ActiveRecord::Base.connection.close if ActiveRecord::Base.connection
    end
  end
end

上述代码由 Yi Zeng 于 2017 年 7 月 16 日发布。你可以把它放在一个名为lib/tasks/to_fixtures.rake. 我将我的 SQL 夹具数据加载到原本为空/干净的测试模式数据库中,然后运行RAILS_ENV=test bundle exec rake db:to_fixtures​​. 它在 Rails 5.2.3 下对我来说按原样工作。

于 2019-07-12T02:01:04.893 回答
0

If you are loading the DB from the script you dumped, that should be all that is in there. If you see anything else I would try dropping the db and recreating it from the script to make sure.

Also, if you just want to load the fixtures, you can run:

rake db:fixtures:load

Update:

You may want to look for a way to include your options in the migrations. In my experiance it nearly always pays off to do things the rails way. If it helps, I would add custom options for using mysql cluster by using the :options option on create table:

class CreateYourTable < ActiveRecord::Migration
  def self.up
    create_table :your_table, :options => "ENGINE=NDBCLUSTER" do |t|
    #...
  end 
end
于 2008-12-23T15:57:59.463 回答