---
title: "Rails 5 Passing current record for custom error"
description:
  "We can now pass the validated record to the proc for generating a custom
  error message."
canonical_url: "https://www.bigbinary.com/blog/rails-5-allows-passing-record-to-error-message-generator"
markdown_url: "https://www.bigbinary.com/blog/rails-5-allows-passing-record-to-error-message-generator.md"
---

# Rails 5 Passing current record for custom error

We can now pass the validated record to the proc for generating a custom error
message.

- Author: Hitesh Rawal
- Published: July 13, 2016
- Categories: Rails 5, Rails

[Active Record](http://guides.rubyonrails.org/active_record_validations.html)
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`.

```ruby

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.](https://github.com/rails/rails/pull/24119)
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.

```ruby

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

```

## Links

- [Human page](https://www.bigbinary.com/blog/rails-5-allows-passing-record-to-error-message-generator)
