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> |
我对为什么仍然显示这种方法有些困惑。我在做什么错?
代替在模型上定义
为了使用
1 | include Mongoid::Attributes::Dynamic |
根据此问题,您需要在
中设置