一张终于又要过去了,这是8的最后一个内容了。终于熬到第九章了要。看书,nnd慢啊。robbin说他们三个人一个月就搞定了整个je,佩服佩服。我一个月这书都没看完,继续努力,继续努力。
这节主要是错误处理,当遇到错误的时候一般做三个事情,记录错误,给出提示信息,然后重新跳到某个指定页面。
rails用rescue表示遇到的某个错误。内置的logger记录错误,每个controller,人人有份在log/development.log下课查看。用flash在网页显示需要显示的错误.redirt_to :action => :xxx重定向。在store_controller下修改如下代码
修改layout/store_layout.html.erb如下
最后在model/cart.rb里面加入统计总额的方法
大功告成
这节主要是错误处理,当遇到错误的时候一般做三个事情,记录错误,给出提示信息,然后重新跳到某个指定页面。
rails用rescue表示遇到的某个错误。内置的logger记录错误,每个controller,人人有份在log/development.log下课查看。用flash在网页显示需要显示的错误.redirt_to :action => :xxx重定向。在store_controller下修改如下代码
def add_to_cart
#@cart = find_cart
#product = Product.find(params[:id])
#@cart.add_product(product)
begin
product = Product.find(params[:id])
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid Product")
else
@cart = find_cart
@cart.add_product(product)
end
def empty_cart #清空session
session[:cart] = nil
redirect_to_index ("Your cart currently is empty")
end
def redirect_to_index(msg) #重定向方法
flash[:notice] = msg
redirect_to :action => :index
end
修改layout/store_layout.html.erb如下
<% if flash[:notice] -%>
<div id="notice"><%= flash[:notice] %></div>
<% end -%>
最后在model/cart.rb里面加入统计总额的方法
def total_price
@items.sum {|item| item.price}
end
大功告成