<-- 2010 January | lorennorman.com

January 7, 2010

MongoMapper with Formtastic: Almost Perfect

Category: web development — loren @ 3:13 pm

I finally dipped my toes into MongoDB last night after catching some inspiration from the Ruby community. But I hit a basic snag doing something that would be Really Freaking Cool if it worked (and by all accounts it SHOULD work!), so in lieu of doing any real work yet I thought I’d post and get some feedback first.

Mongo is one these new-fangled NoSQL databases, which means it’s schemaless and doesn’t require migrations. So how do you manage your data? Grab a Mongo library and start defining some models!

I’m partial to John Nunemaker’s MongoMapper, here’s a snippet to show how easy it is to play:

Note: Another nice Ruby-Mongo library is Mongoid by the nice folks at Hashrocket.

So I read this MongoMapper post on bitzesty yesterday (lots of nice examples there, as well) which goes so far as to mention a few powerful Ruby gems that are MongoMapper-compatible. Amongst them was Formtastic, a semantic form builder for Rails which I am already a great fan of. And therein lies the Really Freaking Cool thing I mentioned earlier: you see, Formtastic supports this awesome syntax for auto-generating a form based on the attributes present in a model:

Really Freaking Cool Thing: While you’re still prototyping your data model, why should you have to make changes to all of your forms (new, edit, other nested forms, etc) when you make a change to your model? You shouldn’t! Just make a quick adjustment to the model and let the forms fall out.

It was this magical world of instantly-propagated data changes with no migrations and no view templates that made me jump in and give it a shot. Alas, an error:

Action Controller: Exception caught
Uploaded with plasq‘s Skitch!

Looks like MongoMapper doesn’t quite walk or talk like an ActiveRecord duck in this case, but that doesn’t seem too hard to fix. I’ll have some time to get to it this weekend, but I wanted to see if anyone else (preferably the maintainers of these plugins!) had an opinion before I dig deeper. The normal Formtastic fields work fine, but if you rely on reflection (call ‘form.inputs’ without specifying attributes), you get this ‘reflections’ error.

This might actually be a trivial one-line fix in MongoMapper, I just haven’t looked at the source, yet. I’m doubting Formtastic needs to do anything right now, but one can’t help dreaming of the coming Rails 3 world where things like this can be loosely coupled yet tightly integrated with little/no work…

This IS a cool idea, isn’t it? Having not totally grokked the new way of thinking with schemaless DBs, I still question all of my instincts in the area. But this just seems like a natural reduction of overhead for dealing with these far-less-strict data sources, especially early in the prototyping phase of a new app!

Your thoughts welcome!