アトラシエの開発ブログ

株式会社アトラシエのブログです

Railsでfull_messagesを加工したい

基本的にRailsのvalidationは

class Blog < AR::Base
  validates :title, presence: true
  validate :title_or_content_needed
end

のようなとき、@blog.errors.full_messagesにはattribute名 + エラー本文に加工されます。 ところで、title_or_content_neededのようにattributeをまたいだり、特定のattributeによらないバリデーションの場合メッセージはattribute名を含まないでほしいことがあります。

地味ですがこういうときにbaseという特別なattributeを指定でき、

def title_or_content_needed
  if title.blank? && content.blank?
    errors.add(:base, :title_or_content_needed)
  end
end

という指定が可能です。辞書ファイル側でtitle_or_content_neededを"タイトルかコンテンツは必須です"のように定義すると、full_messagesでもそのまま出力されます。