[英]Shopping cart : handling no product error with rails / ajax
I am using ajax to change the displayed cart as the user add product to cart. 当用户将产品添加到购物车时,我正在使用ajax更改显示的购物车。 To do so i call with :remote=>true the correct controller that send back the updated cart.
为此,我用:remote => true调用正确的控制器,该控制器会发送回更新的购物车。 The controller method to do so is the following :
这样做的控制器方法如下:
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(magasin_url) }
format.js {@current_item = @line_item }
format.xml { render :xml => @line_item, :status => :created, :location => @line_item }
else
format.html { render :action => "new" }
format.xml { render :xml => @line_item.errors, :status => :unprocessable_entity }
end
end
end 结束
I'd like to be able to handle an empty stock by sending a notice message instead of updating the cart. 我希望能够通过发送通知消息而不是更新购物车来处理空库存。
I tried this : 我尝试了这个:
if product.stock_to_display <=0
respond_to do |format|
format.html { }
format.js {}
end
end
But i do not know what to put in the format. 但是我不知道该用什么格式。 and i have no idea how to do a condition in the rjs :
而且我不知道如何在rjs中执行条件:
page.replace_html('panier', render(@cart))
page[:panier].visual_effect :blind_down if @cart.total_items == 1
page[:current_item].visual_effect :highlight,
:startcolor => "#88ff88",
:endcolor => "#114411"
page.select("#notice").each {|notice| notice.hide}
So i'd like to know how to handle the error with ajax/rjs. 所以我想知道如何使用ajax / rjs处理错误。 Thanks
谢谢
Ok after a little bit of try i managed to do something that seems clean. 好了,经过一番尝试,我设法做了一些看起来很干净的东西。
I created a @success boolean in the controller and affected him a value, after that i can use the boolean in RJS to either do my stuff or display the notice. 我在控制器中创建了一个@success布尔值,并影响了他一个值,之后我可以在RJS中使用布尔值来做我的工作或显示通知。 Here is my new RJS.
这是我的新RJS。
if @success
page.replace_html('panier', render(@cart))
page[:panier].visual_effect :blind_down if @cart.total_items == 1
page[:current_item].visual_effect :highlight,
:startcolor => "#88ff88",
:endcolor => "#114411"
page.select("#notice").each {|notice| notice.hide}
else
page.replace_html :notice, flash[:notice]
flash.discard
end
If you have a javascript error with the display, check the application layout as it may be restricted by a "if notice" condition 如果显示屏出现javascript错误,请检查应用程序布局,因为它可能会受到“如果通知”条件的限制
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.