我正在努力从"敏捷Web开发与rails"一书中创建depot应用程序。我想更改其功能,以便购物车不出现在侧列中,而是得到一个包含"(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
的代码 - 我将如何在应用程序布局视图中引用它,因为这是我想要的值?谢谢!
我会在您的购物车中添加一个名为 item_count 的方法,该方法将购物车中的项目数量相加。
def item_count
line_items.inject{|sum, line_item| sum + line_items.quantity
end
然后在应用程序布局视图中,您可以简单地引用 @cart.item_count。