2012-06-21 34 views
1

我正在通過從本書'帶導軌的敏捷web開發'創建倉庫應用程序。我想改變它的功能,以便代替購物車出現在側欄中,而是通過'(x)目前在您的購物車中的物品'獲得一個聲明。擴展'車廠'應用程序,以包括購物車中的總項目

我有這樣的代碼:

line_items控制器(即是在車中的項目):

def create 
@cart = current_cart 
product = Product.find(params[:product_id]) 
@line_item = @cart.add_product(product.id) 

respond_to do |format| 
    if @line_item.save 
    format.html { redirect_to store_url } 
    format.js { @current_item = @line_item } 
    format.json { render json: @line_item, 
     status: :created, location: @line_item } 
    else 
    format.html { render action: "new" } 
    format.json { render json: @line_item.errors, 
     status: :unprocessable_entity } 
    end 
end 
end 

和車控制器:

def show 
begin 
    @cart = Cart.find(params[:id]) 
rescue ActiveRecord::RecordNotFound 
    logger.error "Attempt to access invalid cart #{params[:id]}" 
    redirect_to store_url, notice: 'Invalid cart' 
else 
    respond_to do |format| 
    format.html # show.html.erb 
    format.json { render json: @cart } 
    end 
end 
end 

如何引用購物車從應用程序佈局視圖,以便我可以將'(x)物品'更改爲購物車中當前的物品數量?我試過@total_cart.line_items以及我能想到的所有其他變化。

編輯:我有購物車模型中的代碼current_item.quantity - 我應該如何在應用程序佈局視圖中引用它,因爲這是我想要的值?謝謝!

回答

0

我會在購物車中添加一個名爲item_count的方法,該方法會將購物車中的物品數加起來。

def item_count 
    line_items.inject{|sum, line_item| sum + line_items.quantity 
end 

然後在你的應用程序佈局來看,你可以簡單地引用@ cart.item_count。

相關問題