【问题标题】:How to implement custom type in mongomapper如何在 mongomapper 中实现自定义类型
【发布时间】:2010-12-24 18:33:43
【问题描述】:

我想要以下模型结构:

Item
  name
  options
    price
      value
      currency
    weight

用于拨打电话:

item.name #name of the item
item.options #options hash
item.options.price.value #item's price
item.options.price.currency #item price's currency
item.options.weight #item's weight

不要问我为什么想要这样的结构。请解释一下自定义类型在 mongomapper 世界中的工作原理...

【问题讨论】:

    标签: ruby-on-rails mongodb mongomapper


    【解决方案1】:

    听起来您实际上想使用embedded documents

    class Item
      include MongoMapper::Document
    
      key :name, String
      one :options, :class_name => "Option"
    end
    
    class Price
      include MongoMapper::EmbeddedDocument
    
      key :value, Float
      key :currency, String
      belongs_to :option
    end
    
    class Option
      include MongoMapper::EmbeddedDocument
    
      key :weight, Float
      one :price
      belongs_to :item
    end
    

    在 mongo 中,这将被存储为:

    {
      "_id" => BSON::ObjectId('4d9bf8e8516bcb45ec000001'),
      "name" => "name",
      "options" => {
        "_id" => BSON::ObjectId('4d9bf92a516bcb45ec000002'),
        "weight" => 1.0,
        "price" => {
          "_id" => BSON::ObjectId('4d9bfa04516bcb45ec000003'),
          "value" => 1.0,
          "currency" => "rubies"
        }
      }
    }
    

    或者,如果您实际上要求为a custom type (glance at the example) 提供一个人为的示例,您可以将该结构存储为一个哈希并将整个内容加载到StructOpenStruct 中,或者只是滚动您自己的类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-14
      • 2018-09-06
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多