Reputation: 73
i have a rails app that currently uses activerecord to store and query products.
Each product has a category and sub category and each sub category is defined by multiple field that i can create within the application. From this when a user wants to input a specific product, they are pressented with the relevent form fields.
This has become very complex and having since hearing about mongodb and mongomapper, i think or wish i created it from the start in using mongomapper !!!
Problem is i want to know the best way to model this app in mongodb ???
I was thinking of having a procuct model with common fields and then having category models inheriting from product model with the different fields in.
Does this sound correct ?
Problem is as well is that i want the user to be able to create there own category and fields from within the application. How can i do this as when a user for example creates a cars category with fields like speed and number of doors etc. I then need to be able to create a form using these fields for future cars to be inputted.
Any ideas, pointers or examples anyone can help me with would be great.
Thanks alot in advance rick
Upvotes: 1
Views: 520
Reputation: 45307
OK, I am not a Ruby/Mongomapper expert, so I won't be able to map this into "models". However, if you look at this from Mongo's perspective, here's how you probably want the data to look in Mongo.
Collection: Category
{"_id" : "car"}
{"_id" : "vintage_car", "parent" : "car", "fields" : ["year" : "integer", "original_parts" : "boolean", "upgrades" : "text"] }
Collection: Products
{"_id" : "1234", "name" : "Model-T", "category" : "car", "sub-category" : "vintage_car", "values" : ["year" : 1942, "original_parts" : false, "upgrades : "XM Radio"] }
So what you have here is pretty simple. You have one collection that contains all of the Categories and Sub-categories. If an object is a "Sub-category" it will have a "parent" field set. If there's no "parent" field, then that object is a "Category".
Each Sub-category has a "fields" element. "fields" is actually an array of pairs. This will make it easy to render. If someone enters a vintage car, you look up the "vintage car" Category and then loop through the "fields" to render the appropriate input boxes. I used simple things like "integer" and "boolean", but you can really put whatever you want in here ("datepicker", "checkbox", ...) it's all up to you.
Now the product itself basically stores a reference to both the Category and Sub-category. It also stores the values for all of the fields that you've input.
So the Product has all of the data it needs, which should make each product pretty easy to render. Load the Product and the appropriate Sub-Category and you'll have all of the info you need to dynamically render the page.
EDIT
In reply to the comment, the "fields" in Category can be built with a unit of measure:
..."fields" : [{"length","meters","float"},{"weight","kg","float"},...]
Upvotes: 1