Reputation: 8432
I'm trying to dynamically add keys to MongoMapper documents.
def build(attrs={})
doc = self.new
apply_scope(doc)
doc.set_up_keys!
doc.attributes = attrs
doc
end
def set_up_keys!
return unless form
form.fields.each do |f|
next if self.keys.include?(f.underscored_name)
self.class.send(:key, f.underscored_name, f.keys['default'].type, :required => f.required, :default => f.default)
end
end
The code in question is available here and here.
form
is a related model. I want to create keys on the current model (self) based on what form#fields
has.
The problem is that if I create two models, they both have the same keys from both models.
self.class.send(:key...)
adds the keys to the model.
Why are they being added to both models?
Is it because the method is being called in a class context?
How can I affect only the individual instance?
Upvotes: 2
Views: 75
Reputation: 37409
Mongomapper defines a model by its class. All instances of this class share the model's keys. If you want to create a model on-the-fly, you will probably need to dynamically create a class, and add the keys to it:
def build(attrs={})
c = Class.new(self.class)
doc = c.new
apply_scope(doc)
doc.set_up_keys!
doc.attributes = attrs
doc
end
Upvotes: 2