我们在 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]