开发者

How to implement custom type in mongomapper

I want the following model structure:

Item
  name
  options
    price
      value
      currency
    weight

for making the calls:

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

Don't ask me why I want such structure. Expla开发者_如何转开发in me please how custom types works in mongomapper world...


It sounds like you're actually wanting to use 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

In mongo, this will be stored as:

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

Or if you're actually asking for a contrived example for a custom type (glance at the example) you could just store that structure as a Hash and just load the whole thing into a Struct, OpenStruct, or just roll your own class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜