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