Shopping cart checkout

IBUNHABIBU IBUNHABIBU posted on 2022-12-23 08:00:15 UTC

Concerning the lesson for the shopping cart with turbo. I've also added user authentication and authorization. I need the admin to be able to see all orders of all customers and their state, whether in process or shipped, and the normal user to be able to access all order history. Can you assist me in making this association?


David Kimura PRO said over 1 year ago :
You would need an Order model that belongs to the user. Once the order has been placed, you, as an admin, could query all of the orders and their statuses. As a user, they should be able to query just their orders since there is a relationship to the user.

IBUNHABIBU said about 1 year ago :
Thank you, I have managed to create an order. Now the issue is when the order is created I need to destroy the cart but doing so caused the cart_item to be nil becauseĀ 
cart has many cart_item dependent: :destroy 
So I will not be able to display the total order price in the order index page as shown below
<strong>Total price </strong> <%= order.cart_items.sum(&:total_price) %>

But in the orders controller, I need to destroy the cart
class OrdersController < ApplicationController
  
  def create
    @order = Order.new(order_params)
    current_cart.cart_items.each do |item|
      @order.cart_items << item 
    end

    @order.user = current_user 
    @order.save
    Cart.destroy(session[:cart_id])
    session.delete(:cart_id)
    redirect_to orders_path, notice: "Thank you for your order"
  end

  private
    def set_order
      @order = Order.find(params[:id])
    end
    def order_params
      params.require(:order).permit(:pay_method)
    end
end


What is the right way to delete the cart?


Login to Comment
Back to forums