关于ruby:蒙古语中的不确定方法

undefine methods in mongoid

我希望能够动态取消定义Mongoid字段。我在类对象的上下文中尝试了undef方法。不幸的是,它不起作用,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
class MongoTest
  include Mongoid::Document
  field :abc, type: Integer
  field :def, type: String
end

m = MongoTest.new
m.fields.keys
 => ["_id","abc","def"]

MongoTest.class_eval { undef :abc, :abc= }
m.fields.keys
=> ["_id","abc","def"]

但是undef实际上确实将方法定义为无法调用:

1
2
m.abc
NoMethodError: undefined method `abc' for #<MongoTest _id: 554013e86d61632f57000000, abc: nil, def: nil>

我对为什么仍然显示这种方法有些困惑。我在做什么错?


代替在模型上定义static字段并尝试在运行时删除它们,应首先使用dynamic字段。

为了使用dynamic字段,必须在模型中添加以下行:

1
include Mongoid::Attributes::Dynamic

根据此问题,您需要在mongoid.yml

中设置allow_dynamic_fields: true