问题描述
我有一些带有初始数据的设备,这些数据需要驻留在我的数据库中(国家,地区,运营商等).我有一个任务rake db:seed,它将为数据库播种.
I have fixtures with initial data that needs to reside in my database (countries, regions, carriers, etc.). I have a task rake db:seed that will seed a database.
namespace :db do
desc "Load seed fixtures (from db/fixtures) into the current environment's database."
task :seed => :environment do
require 'active_record/fixtures'
Dir.glob(RAILS_ROOT + '/db/fixtures/yamls/*.yml').each do |file|
Fixtures.create_fixtures('db/fixtures/yamls', File.basename(file, '.*'))
end
end
end
我有点担心,因为此任务清除了我的数据库并加载了初始数据.甚至可以在生产中执行不止一次的事实使我不知所措.这是正常现象吗,我只需要保持谨慎?还是人们通常以某种方式保护这样的任务?
I am a bit worried because this task wipes my database clean and loads the initial data. The fact that this is even possible to do more than once on production scares the crap out of me. Is this normal and do I just have to be cautious? Or do people usually protect a task like this in some way?
推荐答案
用夹具填充数据是一个非常糟糕的主意.
Seeding data with fixtures is an extremely bad idea.
未验证固定装置,并且由于大多数Rails开发人员不使用数据库约束,这意味着您可以轻松地将无效或不完整的数据插入到生产数据库中.
Fixtures are not validated and since most Rails developers don't use database constraints this means you can easily get invalid or incomplete data inserted into your production database.
默认情况下,固定装置还设置奇怪的主键ID,这不一定是问题,但很烦人.
Fixtures also set strange primary key ids by default, which is not necessarily a problem but is annoying to work with.
有很多解决方案.我个人最喜欢的是一个rake任务,该任务运行一个仅使用ActiveRecord插入记录的Ruby脚本.这就是Rails 3使用db:seed
的方式,但是您可以自己轻松地编写此代码.
There are a lot of solutions for this. My personal favorite is a rake task that runs a Ruby script that simply uses ActiveRecord to insert records. This is what Rails 3 will do with db:seed
, but you can easily write this yourself.
我用添加到ActiveRecord :: Base的方法create_or_update
补充了这一点.使用此工具,我可以多次运行种子脚本,更新旧记录,而不是引发异常.
I complement this with a method I add to ActiveRecord::Base called create_or_update
. Using this I can run the seed script multiple times, updating old records instead of throwing an exception.
不久前,我写了一篇有关这些技术的文章,名为加载种子数据.
I wrote an article about these techniques a while back called Loading seed data.
这篇关于在Ruby on Rails中使用固定装置播种数据很危险的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!