我正在通过“使用rails进行敏捷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 :(得分:0)
我会在您的购物车中添加一个名为item_count的方法,该方法会累计购物车中的商品数量。
def item_count
line_items.inject{|sum, line_item| sum + line_items.quantity
end
然后在您的应用程序布局视图中,您可以简单地引用@ cart.item_count。