Skip to content

Commit

Permalink
Document message validation option accepts Proc
Browse files Browse the repository at this point in the history
  • Loading branch information
eliotsykes committed Nov 27, 2015
1 parent 9d7d12c commit d160470
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion guides/source/active_record_validations.md
Original file line number Diff line number Diff line change
Expand Up @@ -777,7 +777,36 @@ Topic.create(title: nil).valid? # => true
As you've already seen, the `:message` option lets you specify the message that
will be added to the `errors` collection when validation fails. When this
option is not used, Active Record will use the respective default error message
for each validation helper.
for each validation helper. The `:message` option accepts a `String` or `Proc`.

A `String` `:message` value can optionally contain any/all of `%{value}`,
`%{attribute}`, and `%{model}` which will be dynamically replaced when
validation fails.

A `Proc` `:message` value accepts two arguments: a message key for i18n, and
a hash with `:model`, `:attribute`, and `:value` key-value pairs.

```ruby
class Person < ActiveRecord::Base
# Hard-coded message
validates :name, presence: { message: "must be given please" }

# Message with dynamic attribute value. %{value} will be replaced with
# the actual value of the attribute. %{attribute} and %{model} also
# available.
validates :age, numericality: { message: "%{value} seems wrong" }

# Proc
validates :username,
uniqueness: {
# key = "activerecord.errors.models.person.attributes.username.taken"
# data = { model: "Person", attribute: "Username", value: <username> }
message: ->(key, data) do
"#{data[:value]} taken! Try again #{Time.zone.tomorrow}"
end
}
end
```

### `:on`

Expand Down

0 comments on commit d160470

Please sign in to comment.