如何在mongomapper中实现自定义类型

时间:2010-12-24 18:33:43

标签: ruby-on-rails mongodb mongomapper

我想要以下模型结构:

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世界中运作...

1 个答案:

答案 0 :(得分:0)

听起来你实际上想要使用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或者滚动你自己的课程。

相关问题