1

The Capturing an Order chapter in Agile Wed Development with Rails uses the following code:

# orders_controller.rb
def create
    @order = Order.new(params[:order])
    @order.add_line_items_from_cart(current_cart)
    if @order.save
      Cart.destroy(session[:cart_id])
      session[:cart_id] = nil
      redirect_to store_url
    else
      @cart = current_cart
      render 'new'
    end
end

  # order.rb
  def add_line_items_from_cart(cart)
    cart.line_items.each do |item|
      item.cart_id = nil
      line_items << item
    end
  end

How does the cart retain its line items when there's a validation error? The add_line_items_from_cart runs before we know whether the order is valid or not. It associates the line items with the order, then sets the item.cart_id to nil:

item.cart_id = nil
self.line_items << item # self is an instance of `Order`.

When I submit an empty form then view the cart, all the line items are still there. How is this possible? What have I missed?

4

1 回答 1

1

The cart is only destroyed when the order is saved. So I guess it will never lose the items. What happens is when you create the order it probably destroy the current cart and the it creates a new one.

于 2013-03-30T22:45:57.953 回答