Update total stock of products

0

I am trying to create a stock from the new products that are created with the System Purchases.

All Compras have a ItemCompra , with a certain product_id and product.quantity , these are nested using a accepts_nested_attributes_for and the relation has_many to model Compras .

Assuming that in my model Compra I created a ItemCompra with a Product_id specific, * for example: ItemCompra = Blue Shoes (: id = > 14,: product_id = > 5, : quantity = > 100) . How do I update the amount for the Blue Shoes Product created earlier in the ItemCompra ? This would be in the table Products of the system, Blue Shoes, :cantidad_disponible

Product.find (5) .update (: quantity_available) (Blue shoes in the system, default = 0)

I would like to do it with a before_save , since every time I add a new product to X purchase, the total for each product should also be updated.

Model Purchase

    class Compra < ActiveRecord::Base
     belongs_to :product
     has_many :item_compras, :dependent => :destroy
     accepts_nested_attributes_for :item_compras, 
     reject_if: RejectDeeplyNested.blank?,
     :allow_destroy => true

     before_save :charge_stock

     private

     def charge_stock
        #Aquí debería cargar el stock para cada product_id
     end
end

ItemCompra model

class ItemCompra < ActiveRecord::Base
    belongs_to :compra
    belongs_to :product
    belongs_to :calibre

    private
end

Product Model

class Product < ActiveRecord::Base
    has_many :compras, :dependent => :restrict_with_error 
    has_many :compra_almacens, :dependent => :restrict_with_error
    has_many :item_compras

    def to_s
        "#{name} #{tipo}"
    end

end
    
asked by Mosiah Ricardo 19.06.2017 в 14:36
source

1 answer

1

Yes you can do it in a callback as before_save , but do it directly in the model ItemCompra which really indicates the effect in the item ; and I would also recommend doing it with after_save (instead of before_save ), so as not to change the inventory until the value has already been saved in ItemCompra :

class ItemCompra < ActiveRecord::Base
    after_save :charge_stock

    belongs_to :compra
    belongs_to :product
    belongs_to :calibre

    private
    def charge_stock
        inventario = product.cantidad_disponible + cantidad
        self.product.update!(cantidad_disponible: inventario)
    end
end

With after_save the charge_stock method will run until ItemCompra has been saved, which will prevent the inventory of the product from increasing when the ItemCompra is not saved.

    
answered by 19.06.2017 / 14:51
source