如何在Mongoid中创建可选引用/嵌入?

时间:2012-09-25 06:07:29

标签: mongodb mongoid nosql

我们在Mongoid中有一个Item数据库,我们为不同的项目存储上下文,可选的额外字段,例如:

class Item
  include Mongoid::Document

  field :name, type: String
end

所以我可以这样做:

a = Item.new
a.name = "Potato Chips"
a[:flavor] = "Barbecue"
a.save
b = Item.new
b.name = "Underwear"
b[:size] = "XL"
b.save
> Item.first.flavor
 => "Barbecue" 
> Item.last.size
 => "XL"

但是,我们想说:

class Flavor
  include Mongoid::Document

  field :name, type: String
  field :ingredients, type: Array
end

如果你这样做了:

f = Flavor.create({name: "Barbecue", ingredients: ["salt", "sugar"]})
a[:flavor] = f
a.save

你得到:

NoMethodError: undefined method `__bson_dump__' for #<Flavor:0x007fb34d3c1718>

我如何做到这一点,我可以去:

Item.first.flavor.ingredients[0]

0 个答案:

没有答案