2009-01-29 135 views

回答

24

這是一個rake任務。如果需要,您可以指定RAILS_ENV;默認是開發環境:

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

db:fixtures:dump on Rails?我沒有在2.3.5上看到它。 – Pablo 2010-02-02 14:52:25

+4

看起來像是從ActiveRecord中提取的。你可以用這個插件添加回去: http://github.com/topfunky/ar_fixtures 然後運行:耙分貝:燈具:轉儲MODEL = MODELNAME – 2010-04-16 05:43:31

+0

這是唯一有效的爲Rails 3 – fotanus 2013-05-08 20:37:31

21

我一直在使用YamlDb來保存我的數據庫的狀態。

用下面的命令來安裝它:

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

使用耙子任務轉儲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

當前保持庫現在是http://github.com/ludicast/yaml_db – Sney 2010-04-18 17:01:52

+1

如何將一個表的目標轉儲,而不是轉儲整個數據庫? – 2013-08-19 18:01:33

2

rake db:fixtures:dump

已更改爲

rake db:extract_fixtures

9

這個插件可以添加你想要的功能。它是從ActiveRecord中提取的,因此不再默認出現。

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

然後運行:

rake db:fixtures:dump MODEL=ModelName

6

對於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非常適合轉儲和保存數據庫,但其格式與夾具不兼容。

1

這裏有一個耙的任務,將恰恰如此(在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

4

Iron Fixture Extractor是出於這樣的目的建造的。對於不同測試場景使用不同夾具套件的情況(尤其適用於所有測試的所有夾具),這種情況特別有用。它提供了用於提取,加載,重建夾具,截斷表格或從夾具yaml文件中截取特定散列的功能。

0
> rails c 
irb> puts Modelname.all.to_yaml 

然後複製&粘貼到文件並編輯它來搭配什麼燈具期待。

這是手工勞動,但如果你只需要一次這可能是最快的方式。

相關問題