我已经看到一些插件和自定义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这样的主要发行工具正在使用它,我不必担心支持/长寿问题。
我认为这最接近我会找到的“标准”。
感谢所有出色的回复。
答案 0 :(得分:14)
这听起来像你应该使用db / seeds.rb和相关的rake db:seed任务。这些是专门为加载种子数据而设计的。然后,您可以拨打YamlDB 加载数据并rake 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
我找到了这个here并为Rails3略微修改了它。
答案 1 :(得分:11)
Heroku使用YamlDB Gem
答案 2 :(得分:2)
没有标准方式来执行此操作。只是加载灯具的标准方法:
rake db:fixtures:load
但互联网上有很多例子:
答案 3 :(得分:1)
它没有使用与db:fixtures完全相同的格式:load会期望,但是ar_fixtures使得转储和加载数据非常容易。
答案 4 :(得分:1)
我认为,如果是标准的管理员信息,您最好将其放入迁移中。理想情况下,灯具应仅用于测试。
答案 5 :(得分:1)
对于其他任何人现在发现这一点,我稍微修改了@jpgeek的答案。在忽略列表中包含schema_migration
表并按ID排序,因此我得到的输出table_name_001
为ID=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