簡體   English   中英

在navbar Rails應用中顯示購物車數量而不是購物車總價

[英]Showing Number of Cart Items instead of Cart total price in navbar Rails app

在我的rails應用程序中,我的_navbar.html.erb有此代碼

            <% if @cart.total_price > 0 %>
                <%= link_to @cart do %> 
                    <i class="fa fa-shopping-cart"> &euro; </i>
                <%=  @cart.total_price %>
                <% end %>

                <% else %>
                    <a href="#" class="menu-cart"><i class="fa fa-shopping-cart"></i> &euro; 0.00</a>
                <% end %>

它顯示@cart.total_price但我希望它顯示購物車中的全部項目。

我不確定該怎么做

這段代碼大部分來自Udemy教程,但是根據我的經驗來說,它變得無關緊要,因此我對嘗試根據自己的需求進行修改感到迷失。

我一直在嘗試將@product_item添加到上面的代碼中,但是很幸運,任何人都可以看看這個並指導我完成這個過程。

我在application_controller.rb有此代碼

before_action :set_cart    

def set_cart
   @cart = Cart.find(session[:cart_id])
   rescue ActiveRecord::RecordNotFound
   @cart = Cart.create
   session[:cart_id] = @cart.id
end

carts_controller.rb我有這個:

class CartsController < ApplicationController

before_action :set_cart, only: [:show, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart

def new
    @cart = Cart.new
end

def show
     @images  = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]
 @random_no = rand(5)
 @random_image = @images[@random_no]

end


def destroy
    @cart.destroy if @cart.id == session[:cart_id]
    session[:cart_id] = nil
    redirect_to root_url, notice: 'Your Cart is Empty'
end


private

def set_cart
    @cart = Cart.find(params[:id])
end

def cart_params
    params[:cart]
end

def invalid_cart
    logger_error = 'You are trying to access invalid cart'
    redirect_to root_url, notice: 'Invalid Cart'
end
end

controllers/concerns我有此文件current_cart.rb

module CurrentCart

private

def set_cart
    @cart = Cart.find(session[:cart_id])
    rescue ActiveRecord::RecordNotFound
    @cart = Cart.create
    session[:cart_id] = @cart.id
end
end

然后,我有了product_items_controller.rb並且有以下代碼:

class ProductItemsController < ApplicationController

include CurrentCart

before_action :set_cart, only: [:create]
before_action :set_product_item, only: [:show, :destroy]

def create

    @product = Product.find(params[:product_id])
    @product_item = @cart.add_product(@product.id)
    if @product_item.save
        redirect_to root_url, notice:'Product added to Cart'
    else
        render :new
    end
end

private

def set_product_items
    @product_item = ProductItem.find(params[:id])
end

def product_item_params
    params.require(:product_item).permit(:product_id)
end

end

和相關的模型是cart.rbproduct_item.rb

cart.rb我有以下代碼:

class Cart < ActiveRecord::Base

has_many :product_items, dependent: :destroy

def add_product(product_id)
    current_item = product_items.find_by(product_id: product_id)
    if current_item
        current_item.quantity += 1
    else
        current_item = product_items.build(product_id: product_id)
    end
    current_item
end

def total_price
    product_items.to_a.sum{|item| item.total_price}
end

end

product_item.rb有以下代碼:

class ProductItem < ActiveRecord::Base
 belongs_to :product
 belongs_to :cart
 belongs_to :order


 def total_price
    product.price * quantity
 end

end

你可以重寫@cart代碼在_navbar.html.erb看起來是這樣,它應該工作就像前面的塊,表示的是product_items.count代替的total_price

<% if @cart.product_items.count > 0 %>
  <%= link_to @cart do %> 
  <i class="fa fa-shopping-cart"></i>
  <%= @cart.product_items.count %>
  <% end %>

  <% else %>
     <a href="#" class="menu-cart"><i class="fa fa-shopping-cart"></i> 0 </a>
<% end %>    

如果要在購物車中添加商品總數,只需將Cart模型中product_items上的quantity列的總和取為:

def total_quantity
  product_items.sum(:quantity)
end

然后,您可以從視圖(或其他任何位置)中調用@cart.total_quantity

請注意,通過在product_items上調用sum ,它是一個關系(而不是數組),這將使用SQL直接計算和:

SELECT SUM(`product_items`.`quantity`) FROM product_items
  WHERE `product_items`.`cart_id` = 123

其中123是購物車的ID。

這比對產品項數組 (即product_items.to_a.sum(&:quantity) )調用sum效率更高,后者將加載每個產品項,然后對數量求和。 但無論哪種應該工作,並根據你在做什么,后者sum可能會滿足您的需求更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM