将db转储到rails中的yml fixture的标准方法是什么?

我已经看到一些插件和自定义rake任务将活动数据库转储到固定装置,但我不确定主流技术是什么。

基本上,我想要与rake相反:db:fixtures:load,以便我可以在部署时将基本数据库信息(管理员用户帐户,一个)放入svn中。 我不想手动创建夹具,例如需要很长时间的样本数据。

当我们部署时,我希望能够运行

rake db:migrate rake db:fixtures:load 

并参加比赛。

在rails中执行此操作的最佳/首选方法是什么?

编辑:

所以似乎没有标准的方法来执行db:fixtures:load的相反rake任务。

我不想使用迁移,因为我想要一个标准的方法来为我的所有项目执行此操作,并且我不喜欢在迁移中添加任何可能的管理员帐户的想法。 其次,我一直在重新思考使用灯具的想法。 我决定使用yaml_db,因为它使用rake任务:

 rake db:data:dump rake db:data:load 

数据将在YAML文件中结束而不会破坏测试装置(可能会有所不同,现在我更仔细地考虑这个)。 此外,如果像Heroku这样的主要发行工具正在使用它,我不必担心支持/长寿问题。

我想这最接近我会找到的“标准”。

感谢所有的好评。

这听起来像你应该使用db / seeds.rb和相关的rake db:seed任务。 这些是专门为加载种子数据而设计的。 然后,您可以调用YamlDB来加载数据并调用db:data:dump_dir将所有fixture转储到临时目录,并根据需要将它们复制到种子数据目录。

请注意,这不适用于转储灯具,因为YAML格式不同。 上面提到的ar_fixtures不适用于Rails 3,似乎不再受支持。 对于转储装置,你可能想在lib / tasks / dump_fixtures.rake中尝试这样的东西:

 namespace :db do namespace :fixtures do desc 'Create YAML test fixtures from data in an existing database. Defaults to development database. Specify RAILS_ENV=production on command line to override.' task :dump => :environment do sql = "SELECT * FROM %s" skip_tables = ["schema_migrations"] ActiveRecord::Base.establish_connection(Rails.env) (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name| i = "000" File.open("#{Rails.root}/test/fixtures/#{table_name}.yml.new", 'w') do |file| data = ActiveRecord::Base.connection.select_all(sql % table_name) file.write data.inject({}) { |hash, record| hash["#{table_name}_#{i.succ!}"] = record hash }.to_yaml end end end end end 

我在这里找到了这个,并为Rails3略微修改了它。

没有标准的方法来做到这一点。 只有加载灯具的标准方式:

 rake db:fixtures:load 

但是互联网上有很多例子:

它不使用与db:fixtures完全相同的格式:load会期望,但ar_fixtures使转储和加载数据非常容易。

我认为,如果是标准的管理员信息,您可能最好将其放入迁移中。 理想情况下,灯具应仅用于测试。

对于其他人来说,现在我已经稍微修改了@jpgeek的答案。 在ignore列表中包含schema_migration表并按ID排序,因此我得到的输出是table_name_001ID=1

 namespace :db do namespace :fixtures do desc 'Create YAML test fixtures from data in an existing database. Defaults to development database. Specify RAILS_ENV=production on command line to override.' task :dump => :environment do sql = "SELECT * FROM %s ORDER BY ID" skip_tables = ["schema_info", "schema_migrations"] ActiveRecord::Base.establish_connection(Rails.env) (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name| i = "000" File.open("#{Rails.root}/test/fixtures/#{table_name}.yml.new", 'w') do |file| data = ActiveRecord::Base.connection.select_all(sql % table_name) file.write data.inject({}) { |hash, record| hash["#{table_name}_#{i.succ!}"] = record hash }.to_yaml end end end end end