ruby – 运行时间更改模型与mongodb / mongoid
我必须在一个mongoid模型中添加几个字段,我知道没有使用MongoDB进行迁移,但是如果我没有丢弃数据库,那么导轨将完全“重新生成”数据块,它不会显示或使用新的字段在所有!
什么是最好的方式去这里?有没有比下降/重新打开mongodb更软的东西? 提前致谢 解决方法
一般来说,应该可以在运行时用新的字段来更新旧文档. MongoDB中不需要进行迁移.
您可能想要使用新的字段和默认值来编写rake任务来更新旧的文档. 您可以通过检查每个默认值为零的新字段来找出这些文档. 更新 风格简约: 如果使用默认值定义一个新的字段,只要设置一个新值,就应始终使用此值: 应用程序/模型/ my_model.rb class MyModel include Mongoid::Document field :name,type: String field :data,type: String # NEW FIELD field :note,type: String,default: "no note given so far!" end 如果您查询您的数据库,您应该在扩展名之前获得没有此字段的文档的默认值: (导轨控制台) MyModel.first #=> #<MyModel …other fields…,note: "no note given so far!"> 我用Ruby 1.9.2中的一个新的rails stack和当前的类型进行了测试,应该与其他堆栈一起工作. 更复杂/复杂的风格: 如果您没有设置默认值,那么这个新字段将为零. 应用程序/模型/ my_model.rb class MyModel include Mongoid::Document field :name,type: String end (导轨控制台) MyModel.first #=> #<MyModel …other fields…,note: nil> 那么你可以设置一个耙子任务和迁移文件,如下例所示: LIB /任务/ my_model_migration.rake: namespace :mymodel do desc "MyModel migration task" task :migrate => :environment do require "./db/migrate.rb" end end DB / migrate.rb: olds = MyModel.where(note: nil) # Enumerator of documents without a valid :note field (= nil) olds.each do |doc| doc.note = "(migration) no note given yet" # or whatever your desired default value should be doc.save! rescue puts "Could not modify doc #{doc.id}/#{doc.name}" # the rescue is only a failsafe statement if something goes wrong end 使用rake mymodel运行此迁移:migrate. 这只是一个起点,您可以将其扩展到完整的mongoid迁移引擎. 任务:migrate => :环境做…是必要的,否则rake不会加载模型. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |