ruby-on-rails - 在 Mongoid 中重命名字段不会更新类中的字段
问题描述
当我在 Mongoid 中重命名一个字段时,它成功更新了 MongoDB 中的字段,但它没有更新 ruby 代码中的字段:
class Example
include Mongoid::Document
field :apple, type: String, as: :c_apple
end
Example.all
=> #<Mongoid::Criteria
selector: {}
options: {}
class: Example
embedded: false>
Example.all.rename("apple" => "d_apple")
MOPED: 127.0.0.1:27017 UPDATE database=core collection=examples selector={} update={"$rename"=>{"apple"=>"d_apple"}} flags=[:multi]
COMMAND database=core command={:getlasterror=>1, :w=>1} runtime: 1.2460ms
=> {"connectionId"=>2, "updatedExisting"=>false, "n"=>0, "syncMillis"=>0, "writtenTo"=>nil, "err"=>nil, "ok"=>1.0}
e = Example.new
=> #<Example _id: 5bfdbf103ed1492f9a000001, apple(c_apple): nil>
e.d_apple
NoMethodError: undefined method `d_apple' for #<Example _id: 5bfdbf103ed1492f9a000001, apple(c_apple): nil>
为什么 MongoDB 中的更改没有反映在类定义中?
解决方案
当你运行时#rename
,你与 MongoDB 交互。文档结构的变化存储在数据库中。该方法不与 ruby 源代码交互,需要自行编辑。
顺便提一句。我不记得与存储在文件中的源代码交互的任何 ruby/rails 方法(除了 rake 任务和生成器中的方法)。
推荐阅读
- python - 如何删除tkinter中按钮之间的空间?
- console-application - 带有 C# 的 SendGrid V3 api 无法从控制台应用程序发送邮件
- java - Gson - CustomObject 内的嵌套对象 - java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap 无法转换为 java.util.List
- python - 基于条件的新列值
- java - c ++中用于联合查找的自引用结构
- python - blpapi.exception.UnsupportedOperationException:快照没有订阅管理端点(0x00080013)
- css - 根据img覆盖svg响应
- r - 如何在 ggplot2 中保存带有特殊字符的 R 图?
- .net - 无法在 VS2019 中构建 CSCORE - 后期构建中的 ilasm 失败
- optaplanner - 计划变量不支持收集