mongodb and mongomapper

后端 未结 1 2012
暖寄归人
暖寄归人 2021-01-24 00:36

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 multipl

相关标签:
1条回答
  • 2021-01-24 01:07

    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"},...]

    0 讨论(0)
提交回复
热议问题