Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Rails's 'can't be blank' error message?

What's the API to access Rails's default can't be blank error message when validation :presence => true fails?

I have the model setup like this:

class TextDocument < Document
  validate :content_not_blank   # 'content' is an attribute

  private
    def content_not_blank
      if content.blank? 
        errors.add(:content, ....?) # I want to access 'can't be blank'
      end
    end
end
like image 318
sivabudh Avatar asked Oct 12 '11 14:10

sivabudh


3 Answers

I18n.t('errors.messages.blank')

should give you what you want.

like image 166
Jared Avatar answered Nov 12 '22 19:11

Jared


Assuming you're using standard yaml translations, you can find the file in ActiveModel

To override it you'd drop a file in your config/locales folder, e.g.:

en:
  errors:
    messages:
      blank: "can't be whatever your custom message"
like image 26
numbers1311407 Avatar answered Nov 12 '22 18:11

numbers1311407


You can just do it with the default method like this:

validates_presence_of(:content)

This will generate the right message (can't be blank) in the current local (if you setup your config/locales/ ..yml files

if you really want to write your own validator

errors.add(:content, I18n.translate(:blank))
like image 1
Cygnusx1 Avatar answered Nov 12 '22 18:11

Cygnusx1