วันอังคาร, กรกฎาคม 03, 2550

อ่าน Agile Web Development with Rails ( 9 )

เก็บหนังสือไปนาน กลับมาอ่านกันต่อครับ

มาดูการจัดการ error บ้าง สิบปากว่าไม่เท่าตาเห็น ดูโค้ดเอาเองก็แล้วกัน

app/controllers/store_controller.rb

def add_to_cart
begin
product = Product.find(params[:id])
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}" )
flash[:notice] = "Invalid product"
redirect_to :action => :index
else
@cart = find_cart
@cart.add_product(product)
end
end

คราวนี้ถ้าเรียก http://localhost:3000/store/add_to_cart/wibble แทนที่จะเจอ error เจ้า error ก็จะไปอยู่ใน log/development.log แล้ว อย่างงว่า wibble คืออะไร สำหรับ Rails แล้ว สิ่งที่ใส่ต่อท้ายก็คือ parameter ID นั่นไงครับ

ปัญหาอีกอย่าคือ error message ที่เราคาดหวังยังไม่โผล่ ต้องไปใส่โค้ดนี้ที่ app/views/layouts/store.rhtml ด้วย

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

โดยทั่วไปจะไว้บบบนสุดก่อนข้อความอื่นใดนะครับ

ไม่มีความคิดเห็น: