Posted: Jul 19, 2009
in development, felipe talk, rails, ruby, software
By Felipe Coury
Polymorphic Associations in MongoMapper
The latest buzz in terms of database in the Rails and Ruby world is MongoDB. It’s not only the hype, though: it’s a solid document-oriented (or schema-free) database which is very fast and scalable.
We’re going to use MongoDB for a couple of new features we’re unleashing in the near future. After doing some research we decided to user John Nunemaker’s stellar (reusing the word he used to describe MongoDB itself) MongoMapper (GitHub).
The DSL MongoMapper provides is really nice. You define your models (or your documents definitions) in a very nice way. Basically each model can be either a Document or an EmbeddedDocument. While the first generates a new document, the former will generate a document that can only be used within another document (or, in other words, as a relation). It’s a nice way to describe a problem domain, without having too much nesting on your logical models. Let me try to explain this with code.
Imagine we have our app domain described by the following code:
See how you can save a Customer instance, but not an Address instance? That’s because an Address doesn’t imply a document per se, it only exists in other documents.
While implementing the feature I tried to create a model inheritance structure, so I could interop between them. Even though this would be achievable without former polymorphic associations, I decided to give it a shot.
After a night of coding, here’s what you can now do with MongoMapper:
I love when I find a library like MongoMapper, but I like it even more when I can give back.
And if you like this addition, you should recommend me here.
Resources:
- => MongoDB Homepage
- => John Nunemaker’s Blog Post about MongoMapper
- => jnunemaker/mongomapper on GitHub
- => fcoury/mongomapper on GitHub (my fork with polymorphic associations)
Until next time,
– Felipe.

