开发者

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 TextDocume开发者_开发技巧nt < 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


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

should give you what you want.


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"


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜