首页 > 解决方案 > 在 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 中的更改没有反映在类定义中?

标签: ruby-on-railsrubymongodbmongoid

解决方案


当你运行时#rename,你与 MongoDB 交互。文档结构的变化存储在数据库中。该方法不与 ruby​​ 源代码交互,需要自行编辑。

顺便提一句。我不记得与存储在文件中的源代码交互的任何 ruby​​/rails 方法(除了 rake 任务和生成器中的方法)。


推荐阅读