Ruby on Rails development from scratch (Windows) (ix)-add error handling to shopping cart

Source: Internet
Author: User
Tags error handling modify ruby on rails

In the last content, we demonstrated how to build a simple shopping cart, this time the content is very simple, to add error handling to the shopping cart.

Concurrent processing is an unavoidable problem for web systems, and we mimic a scenario of concurrent conflict:

1. Users enter the shopping cart page, see a total of 5 kinds of merchandise.

2. The administrator maintains a list of items in the background and deletes one of the 5 items.

3. The customer selects the deleted item and adds it to the shopping cart.

In this case, if you do not do any processing will produce an exception, and we have to do is to deal with this exception, to show the user a product does not exist error prompts.

1. First we need to modify the Storecontroller Add_to_cart method, the following is the code for the Add_to_cart method:

def add_to_cart
Product = Product.find (Params[:id])
@cart = Find_cart
@cart. Add_product (product)
R Edirect_to (: Action => ' Display_cart ')
rescue
Logger.error ("Attempt to access invalid product #{params[:id] } ")
flash[:notice] = ' Invalid product '
redirect_to (: Action => ' index ')
end

2. Modify the index.rhtml file in the Rails_apps\depot\app\views\store directory:

Add the following code after the <div id= "main" > This sentence:

<% if @flash [: notice]-%>
<div id= "notice" >
<%= @flash [: notice]%></div>
< % End-%>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.