Eddie Xie
Eddie Xie

Reputation: 925

rails revert a activerecord update?

Let's say I have a use case where a user can submit an order. This order contains some information of how many items in my inventory. However, a user can also cancel this order after the order is created. In that case, the inventory should be added back.

I'm wondering how shall I implement this in rails? I'm not sure the correct google key words to search for it

Any pointers would be appreciated!

Upvotes: 0

Views: 484

Answers (3)

Manuel Martinez
Manuel Martinez

Reputation: 388

Elaborating on @user2280271's answer I'd build a service object to take care of the logic, and then just call it from the controller, here's a great post on service objects: http://brewhouse.io/blog/2014/04/30/gourmet-service-objects.html

So maybe you'll end up with something like this:

class OrdersController
  def cancel
    @order = Order.find(params[:id])

    if CancelOrder.call(@order)
      redirect_to order_path(@order), notice: 'Your order has been canceled'
    else
      redirect_to order_path(@order), alert: "There's been an error while canceling your order"
    end
  end
end

Upvotes: 0

Piya Pakdeechaturun
Piya Pakdeechaturun

Reputation: 141

I thinks its ok to go straight way to code

inventory has_many items order has_many items

items belong_to order items belong_to inventory

when order created deducts items_amount in inventory when order cancel(remove, destroy) add items_amount in inventory

Upvotes: 0

user2280271
user2280271

Reputation: 43

I think it would be better to implement the logic explicitly. So have an action that deletes the Order and also sets the inventory back to what it should be.

Upvotes: 2

Related Questions