2011-02-26 44 views
8

所以我剛開始在rails 3中使用自定義驗證器,但是我不確定我是否可以使用現有的activerecord i18n語言環境文件。看來,我必須做rails 3 validators&i18n

record.errors[attribute] << I18n.t('activerecord.errors.models.{model}.attributes.{attribute}.invalid_whatever') if ... 

,而不是之前的時候我可能只是做

:message => :invalid_whatever 

是有速記我可以在加載ActiveModel使用方法:驗證/ EachValidator類來完成同樣的事情?

回答

16

我有同樣的問題,終於找到了答案......

record.errors.add(attribute,:invalid_whatever) 
2

如果你最終讀了這個問題(這本書寫的時間是幾歲),你可以嘗試以下爲Rails 4:

在你的模型:
class Document < ActiveRecord::Base validates :date, date_in_present: {message: :custom_message} end

在你驗證:
class DateInPresentValidator < ActiveModel::EachValidator def validate_each(object, attribute, value) if(value.to_date >= Date.today) true else object.errors[attribute] << options[:message] end end end

在你的i18n文件陽明海運:
en: activerecord: errors: models: document: attributes: date: custom_message: Date is not in present

我沒有徹底測試此。

你也可以在自定義驗證指定後備消息:
object.errors[attribute] << (options[:message] || "Display this message if message is not in options")