I have been reading that ActiveRecord Transactions are automatically wrapped around save and destroy actions. My question relates to the following scenario.
I have an inventory system that tracks Shipments and adjusts a Product’s inventory amount when a shipment is created. When I delete a shipment, I have it programmed that the shipment quantities are then added back to the Product’s inventory amount. This scenario is designed for if a user fouls up a shipment. Deleting the shipment will then add the shipped items back into inventory.
My question is when the product_shipments are looped through is it necessary to provide the Product.transaction block or can I omit this since the destroy method is automatically wrapped in a transaction? Is it ok to wrap an entire loop in a transaction like I have? How can I best ensure that all these database operations are rolled back if something goes haywire?
def destroy
@shipment = Shipment.find(params[:id])
@shipments = @shipment.product_shipments
Product.transaction do
@shipments.each do |s|
@difference = -(s.qty_shipped.to_i)
Product.update_inventory_quantities(@difference, s.product_id)
end
end
@shipment.destroy
respond_with @shipment, :location => shipments_url
end
To elaborate on Mischa’s suggestion, ActiveRecord callbacks will allow you to improve this code in several important ways. First, it removes the ugly transaction block that prompted you to write this question. Almost always, if you see a transaction block like that in Rails, you’re probably doing something wrong. Secondly, it starts moving things back to where their concerns are. This will not only make maintenance easier, due to things being in intuitive locations and largely leveraging built-in Rails methods, but it will also make things a great deal easier to test.
I suspect that there are not tests for this application. This might be a good excuse to write a few, as you’re making this adjustment. It’s starting to break down to the point where a few simple specs could go a long way, and your application complexity looks like it may be to the point where you could benefit from the added piece of mind (especially due to money being involved).
I am going to make certain assumptions about your object’s relationships, and leave them out of the example code below, but I was imagining a has_many :through -type situation involving Shipments, Products, and ProductShipments.
Your controller, cleaned up:
Your Shipment model:
Your join model:
Honestly, I would even take it a little further, and make restore_unshipped_inventory in ProductShipment operate on the instance of product (
product.update_inventory_quantities), even if all that instance method did was call the class method you have there, just to further isolate the unrelated logic.