5-13 Rspec實際(筆記)
validates處理驗證錯誤:詳見ActiveModel::Errors文檔
一,errors
ActiveModel::Errors的實例包含所有的?。每個錯誤:key是每個屬性的name, value是一個數組,包含錯誤消息string.
例子:
person = Person.new
person.errors.messages #=> {:name => ["can‘t be blank", "is too short"], ...}
二 ,errors[]
通過key獲取value ,如person.errors[:name] #=> ["can‘t be blank", "is too short"]
三, errors.add(atr, msg) 或者 errors.message[atr] << "msg"
手動添加某屬性的錯誤message
errors.full_message: 友好顯示所有錯誤message(規範了格式,便於閱讀)
full_message等同to_a
四, errors.details,
在add()方法內增加限制參數,not_allowed: "xxx"
五, errors[:base] << "string"
把錯誤message添加到整個對象上。不是針對屬性。不管什麽錯誤,只像把對象標記為無效,就使用這個方法。
六,errors.clear 和 errors.empty?
清除errors 集合中所有message, errors.empty?查看是否錯誤集合是空的,配合clear使用。
七,errors.size,返回錯誤消息總數。 等同errors.count
八,視圖上顯示錯誤消息。
可以使用scarfold,在_form.html.erbzhong 自動加入ERB代碼。或者自己寫。
5-13 Rspec實際(筆記)