Better error messages for validation
Posted by PunNeng, Sat Apr 26 02:38:00 UTC 2008
แว่บๆ ไปอ่าน feed เจอของ Softies on Rails
error_messages_for เปลี่ยนไป(ตอนไหนไม่รู้)
ที่เคยเขียนไปของเก่า จำได้ว่ามันแก้ header_messages ไม่ได้ เลยต้องแก้เอง เพราะหน้าตาใน helper ของเก่าเป็นแบบนี้
1
| header_message = "#{pluralize(count, 'error')} prohibited this #{(options[:object_name] || params.first).to_s.gsub('_', ' ')} from being saved" |
แว่บไปดูใน API ไปเจอว่าเปลี่ยนไปจริงๆ ได้ของแถมมาอีก คือ error_messages_on ซึ่งผมไม่เคยใช้มาก่อน(บ้านนอก)
list ข้างล่างคือค่า params ที่เราจะใส่ไปได้ใน error_messages_for
- header_tag ค่า default เป็น h2
- id ค่า default เป็น errorExplanation
- class ค่า default เป็น errorExplanation
- object ไว้เซ็ตค่ากรณีที่ไม่มี object ที่ต้องใส่ตาม convention เช่น
error_messages_for 'user'
ถ้าจะให้ขึ้น ฝั่ง view จะต้องมองเห็น @user แล้ว error ถึงจะออก
แต่แบบใหม่นี่ สามารถอ้างได้จาก object อื่นได้เลย เช่น
error_messages_for 'user', @question.user
- object_name ตรงตัว ถ้าไม่ใส่ จะไปใช้ object แทน ในตัวอย่างคือ User
- header_message ตรงตัว ค่า default เป็น X errors prohibited this object from being saved ซึ่ง X ก็คือ object_name นั่นแหละ
- message คือข้อความที่อยู่ใต้ header_message และมาก่อน error list ค่า default เป็น There were problems with the following fields:
ถัดมาก็ error_message_on
ไม่มีอะไรง่ายกว่าการดูตัวอย่าง
1 2 3 4 5 6 7 8 | <%= error_message_on "post", "title" %> => <div class="formError">can't be empty</div> <%= error_message_on @post, "title" %> => <div class="formError">can't be empty</div> <%= error_message_on "post", "title", "Title simply ", " (or it won't work).", "inputError" %> => <div class="inputError">Title simply can't be empty (or it won't work).</div> |
ปล. นึกไม่ออกว่าข้อความไหน อยู่ตรงไหน ย้อนกลับไปดของเก่าได้ครับ