我有一个
class Item
include Mongoid::Document
field name, type: String
end
和一个
class Pack
include Mongoid::Document
end
每个包可以包含不同数量的不同项目。
我最初想做
class Pack
include Mongoid::Document
field items, type: Array
end
起初,我尝试
a = Pack.new
a.items = []
a.items << {item: Item.first, quantity: 4}
a.save
我得到了:
NoMethodError: undefined method `__bson_dump__' for #<Item:0x007faf1a56d670>
然后我尝试了:
a = Pack.new
a.items = []
a.items << {item_id: Item.first.id, quantity: 4}
a.save
但现在我不能做类似的事情
a.items[0].item.name
接下来,我尝试了
class Item
include Mongoid::Document
field name, type: String
belongs_to :item_quantity
end
class ItemQuantity
include Mongoid::Document
has_one :item
belongs_to :pack
field quantity, type: Integer
end
class Pack
include Mongoid::Document
has_many :item_quantity
end
哪个有效,但感觉像一个杂物
我怎样才能最好地做到这一点?