inventid / tails

Models on the fly!
MIT License
1 stars 0 forks source link

Duplicate error thrown when it's not #49

Closed rogierslag closed 9 years ago

rogierslag commented 9 years ago

At inventid, we have some of the following code which goes over an array and saves the data in a grouped item (modified code)

Model

class App.Models.OrderProductQuantity extends App.Model
  @hasOne product: ->
    App.Models.Product

  initialize: (product) ->
    super

    @product = product
    @value = 1

  increase: () ->
    @value = @value + 1

  decrease: () =>
    @value = @value - 1

Method

  @getter order_products_quantities: ->
    order_products_quantities = {}
    @get('order_products').forEach ( order_product ) ->
      console.log(order_products_quantities)
      if !order_products_quantities[order_product.get('product').id]?
        order_products_quantities[order_product.get('product').id] = new App.Models.OrderProductQuantity(order_product.get('product'))
      else
        order_products_quantities[order_product.get('product').id].increase()
    console.log(order_products_quantities)
    return order_products_quantities

When theorder_products_quantities is called multiple times, we get a error from tails Error: Duplicate OrderProductQuantity for id 2.. However, this should not be thrown, it seems it checks whether is was previously added to the old object

@joostverdoorn @steffansluis

joostverdoorn commented 9 years ago

Old or not, there can never be two models of the same type with the same id. Look at new App.Models.OrderProductQuantity(order_product.get('product')). Here you're initializing a new OrderProductQuantity and passing the same product to each. It will initialize the OrderProductQuantity with the product's id, which will obviously not work. You're probably looking for this: new App.Models.OrderProductQuantity(product: order_product.get('product'))

rogierslag commented 9 years ago

Never code between 6pm and dinner...