开发者

rails 3 validators & i18n

so i just started using the custom validators in rails 3, however i am not sure if i can use my existing activerecord i18n locale files. it seems that i have to do

record.errors[attribute] << I18n.t('activerecord.errors.models.{model}.attribu开发者_如何学Ctes.{attribute}.invalid_whatever') if ...

instead of before when i could have just done

:message => :invalid_whatever

is there shorthand i can use in my ActiveModel:Validator/EachValidator class to accomplish the same thing?


I had the same problem and finally found the answer...

record.errors.add(attribute,:invalid_whatever)


If you end up reading this question (which by the time of this writing is a few years old), you could try the following for Rails 4:

In your model:
class Document < ActiveRecord::Base validates :date, date_in_present: {message: :custom_message} end

In your validator:
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

In your i18n yml file:
en: activerecord: errors: models: document: attributes: date: custom_message: Date is not in present

I didn't test this thoroughly.

You could also specify a fallback message in the custom validator:
object.errors[attribute] << (options[:message] || "Display this message if message is not in options")

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜