Guest User

Untitled

a guest
Jan 22nd, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. class Item
  2. include Mongoid::Document
  3. field name, type: String
  4. end
  5.  
  6. class Pack
  7. include Mongoid::Document
  8. end
  9.  
  10. class Pack
  11. include Mongoid::Document
  12.  
  13. field items, type: Array
  14. end
  15.  
  16. a = Pack.new
  17. a.items = []
  18. a.items << {item: Item.first, quantity: 4}
  19. a.save
  20.  
  21. NoMethodError: undefined method `__bson_dump__' for #<Item:0x007faf1a56d670>
  22.  
  23. a = Pack.new
  24. a.items = []
  25. a.items << {item_id: Item.first.id, quantity: 4}
  26. a.save
  27.  
  28. a.items[0].item.name
  29.  
  30. class Item
  31. include Mongoid::Document
  32. field name, type: String
  33. belongs_to :item_quantity
  34. end
  35.  
  36. class ItemQuantity
  37. include Mongoid::Document
  38. has_one :item
  39. belongs_to :pack
  40. field quantity, type: Integer
  41. end
  42.  
  43. class Pack
  44. include Mongoid::Document
  45. has_many :item_quantity
  46. end
  47.  
  48. class Item
  49. include Mongoid::Document
  50. has_many :item_instances
  51. end
  52.  
  53. class ItemInstance
  54. include Mongoid::Document
  55. belongs_to :item
  56. belongs_to :pack
  57. end
  58.  
  59. class Pack
  60. include Mongoid::Document
  61. has_many :item_instances
  62. end
  63.  
  64. pack = Pack.new
  65. item = Item.first
  66. pack.item_instances.build(item_id: item.id)
  67.  
  68. pack = Pack.new
  69. product = Product.first
  70. pack.items.build(product_id: product.id)
  71.  
  72. class Pack
  73. def new_item(product)
  74. self.items.build(product_id: product.id)
  75. end
  76.  
  77. def products
  78. self.items.map { |i| i.product }
  79. end
  80. end
  81.  
  82. pack.add_item(product)
  83. # Same as using pack.items.build(product_id: product.id)
  84.  
  85. pack.products
  86. # Returns an array (including duplicates) of all the products included in the pack.
Add Comment
Please, Sign In to add comment