Reputation: 45
I have around 25 items left for a product represented as product.stock = 25
. Say I sell 5 of this specific product. Then I need to update the remaining stock entry for it to 25 - 5 = 20
or product.stock = product.stock - purchase.quantity
.
How would I do this in my app. Would I place the above code somewhere in my controller?
I have a purchasing form that caters to the following:
I am not sure if I am being clear here or if the subject is relevant to my question.
Upvotes: 2
Views: 125
Reputation: 24337
I would use ActiveRecord's decrement! method:
product.decrement!(:stock, purchase.quantity)
If the Purchase model is what tracks the final sale, then I would put this code in an ActiveRecord callback. For example:
class Purchase < ActiveRecord::Base
belongs_to :product
after_create :adjust_inventory
def adjust_inventory
product.decrement!(:stock, quantity)
end
end
Purchase should also have a before_save
validation that ensures enough stock exists to satisfy the order.
Upvotes: 2
Reputation: 2576
The method to decrement your stock should be implemented in the Product model
def decrement_stock(qty)
self.stock = self.stock - qty
self.save
end
In your controller, you should call this method based on your params.
purchase_controller.rb
def update
@product = Product.find(params[:id])
# Add validation to make sure you have any stock
@product.decrement_stock(params[:quantity])
# Add other things you need to do and return the @product
end
This is a fairly simplified version. You should actually have an Order model, an OrderLine model and a Product.
Upvotes: 0