Donato
Donato

Reputation: 2777

undefine methods in mongoid

I want to be able to dynamically undefine mongoid fields. I tried the undef method in the context of the class object. Unfortunately it does not work, as shown below:

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"] 

But undef does actually undefine the method from being invocable:

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

I'm a little confused as to why this method still shows up. What am I doing wrong?

Upvotes: 0

Views: 194

Answers (1)

Mike S
Mike S

Reputation: 11429

Instead of defining static fields on the model and attempting to remove them at runtime, you should use dynamicfields in the first place.

In order to use dynamic fields you must add the following line to your model:

include Mongoid::Attributes::Dynamic

And according to this question you will need to set allow_dynamic_fields: true in mongoid.yml

Upvotes: 1

Related Questions