Rails 5 Passing current record for custom error

Hitesh Rawal

Hitesh Rawal

July 13, 2016

This blog is part of our  Rails 5 series.

Active Record validations by default provides an error messages, based on applied attributes. But some time we need to display a custom error message while validating a record.

We can give custom error message by passing String or Proc to :message.


class Book < ActiveRecord::Base
  # error message with a string
  validates_presence_of :title, message: 'You must provide the title of book.'

  # error message with a proc
  validates_presence_of :price,
      :message => Proc.new { |error, attributes|
      "#{attributes[:key]} cannot be blank."
      }
end

What's new in Rails 5 ?

Rails 5 allows passing record to error message generator. Now we can pass current record object in a proc as an argument, so that we can write custom error message based on current object.

Revised example with current record object.


class Book < ActiveRecord::Base
  # error message with simple string
  validates_presence_of :title, message: 'You must provide the title of book.'

  # error message with proc using current record object
  validates_presence_of :price,
      :message => Proc.new { |book, data|
      "You must provide #{data[:attribute]} for #{book.title}"
      }
end

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.