aboutsummaryrefslogtreecommitdiffstats
path: root/guides
diff options
context:
space:
mode:
authorEliot Sykes <eliotsykes@gmail.com>2015-11-27 14:04:36 +0000
committerEliot Sykes <eliotsykes@gmail.com>2015-11-27 16:50:02 +0000
commitd16047018f513672e5aa7cb4997608b162845db7 (patch)
tree0c57ebf7cf1ca372c580243adca521fe36f52a68 /guides
parent9d7d12c0044751a494162760cd018fb66eab200f (diff)
downloadrails-d16047018f513672e5aa7cb4997608b162845db7.tar.gz
rails-d16047018f513672e5aa7cb4997608b162845db7.tar.bz2
rails-d16047018f513672e5aa7cb4997608b162845db7.zip
Document message validation option accepts Proc
Diffstat (limited to 'guides')
-rw-r--r--guides/source/active_record_validations.md31
1 files changed, 30 insertions, 1 deletions
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index fe42cec158..496fe720a4 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -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`