I figured I would capitalize on DataMapper’s ability to store JSON objects to keep my table nice and trim, but the documentation doesn’t clarify how one should go about querying on JSON values. I’m storing the scores for a basketball game like so:
{"NJN":[15,20,27,23,85],"CLE":[17,17,28,29,91]}
At the moment, to find games in which the Cleveland Cavaliers played, I’m doing this:
Game.all.reject { |g| !g.scores['CLE'] }
This is extremely slow and inefficient. Game.all(:scores['CLE']) throws a NoMethodError, so what is the proper syntax?
It is not intended that you search on the JSON. It is useful to be able to save the JSON in the DB, but if you need to search on it, you need to re-think your schema. DataMapper is not a silver bullet for good database design 😉
Assuming your reasons for using JSON were simply convenience, you should move the JSON-encoded data to a separate model and map it using an association. You can write a migration to convert the records you have currently stored into the new format.