[英]How do I localize custom error messages in rails active record validations?
具體來說,我試圖在此處本地化“ 定制方法”示例。 我發現了一個類似的問題,但我不知道如何在errors.add()方法中傳遞:message參數。 我試圖做這樣的事情:
errors.add(:discount, message: :greater_than_value_error)
但它打印:
{:message=>:greater_than_value_error}
而不是打印.yml文件中的實際錯誤消息。
這里正確的語法應該是什么?
我的.yml文件看起來像這樣(不確定下面的內容是否100%准確):
activerecord: #try to use activemodel here
errors:
models:
invoice: # or namespace/model_name
attributes:
discount:
greater_than_value_error: "can't be greater than total value"
嘗試以下errors.add :field_name, :message
。 errors.add :field_name, :message
rails errors.add :field_name, :message
4。
errors.add(:discount, :greater_than_value_error)
如果您要編寫自定義驗證,則需要進行實際翻譯,
errors.add(:discount, I18n.t(path_to_locale_text))
僅當使用內置方法時,才可以國際化標准驗證消息,例如預定義驗證器greater_than_value_error
。
validates_numericality_of :discount :greater_than => limit
有關更多詳細信息,請訪問https://stackoverflow.com/a/4453350/1232447 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.