Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top