私は
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
これは機能しますが、クラッジのように感じます
これを行うにはどうすればよいですか?