Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}.attributes.{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?

like image 635
brewster Avatar asked Feb 26 '11 08:02

brewster


2 Answers

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

record.errors.add(attribute,:invalid_whatever)
like image 90
Andreas Avatar answered Dec 02 '22 16:12

Andreas


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")

like image 30
Charlie Vieillard Avatar answered Dec 02 '22 16:12

Charlie Vieillard