different keys for documents of the same collection ?

11 views
Skip to first unread message

aurels

unread,
Feb 7, 2012, 8:42:00 AM2/7/12
to MongoMapper
Hello,

This is more a Ruby question but as it's applied to MM, someone could
have an idea.

Let's say I have these 2 models :

class Entity
include MongoMapper::Document

many :instances
end

class Instance
include MongoMapper::Document

belongs_to :entity
end

I would like Instance's objects to have custom keys depending on the
Entity they belongs to.

I tried to add them to the singleton class of each instance like
this :

class Instance
include MongoMapper::Document

belongs_to :entity

def entity=(new_entity)
super

if #some condition about entity#
singleton_class.key(:custom_field, String)
end
end
end

but apparently keys need to be stored in class in order to work.

Does anyone have any idea how I can achieve this ?

Thanks,

Aurélien

John Nunemaker

unread,
Feb 7, 2012, 1:25:02 PM2/7/12
to mongo...@googlegroups.com
I would just do a hash key and store custom data in that.

ie:

key :custom_fields, Hash

Then you can dump anything you want in that.
--
You received this message because you are subscribed to the Google
Groups "MongoMapper" group.
For more options, visit this group at

aurels

unread,
Feb 7, 2012, 2:26:33 PM2/7/12
to MongoMapper
I had this idea too but validating these fields is not out of the box
anymore (as the keys in the hash aren't true attributes).

What I did :

class Instance
class << self
def for_entity(entity)
klass = Class.new(self)
name = "InstanceOf#{entity.id}"

if #some condition about entity#
klass.key(:blop, Integer)
end
...

Instance.const_set(name, klass)
klass
end
end
end

Instance.for_entity(Entity.first).new

It works well but it defines a lot of classes in Instance's namespace.

Aurélien

John Nunemaker

unread,
Feb 10, 2012, 3:15:42 PM2/10/12
to mongo...@googlegroups.com
Just write a custom validation to validate the keys in the hash if that is necessary. 

validate :foo

def foo
  if custom_fields[:something].blank?
    errors.add(:base, "Something was blank")
  end
end
Reply all
Reply to author
Forward
0 new messages