aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/active_record_validations.md
diff options
context:
space:
mode:
authorSteve Klabnik <steve@steveklabnik.com>2012-11-29 15:24:08 -0800
committerSteve Klabnik <steve@steveklabnik.com>2012-12-01 10:25:16 -0800
commit55a2820cc6d33e96b8d1b64b38b033913058dce4 (patch)
treec8a95b5807d1587a8c245723f653e8e51e194990 /guides/source/active_record_validations.md
parent0181c2da977fc3de4e4c4eac602b26ff180cda2c (diff)
downloadrails-55a2820cc6d33e96b8d1b64b38b033913058dce4.tar.gz
rails-55a2820cc6d33e96b8d1b64b38b033913058dce4.tar.bz2
rails-55a2820cc6d33e96b8d1b64b38b033913058dce4.zip
Here's a few updates to the validations guide. A bunch of small changes,
plus: * 80 column formats * replacing the explanation of the dynamic_form gem with the example HTML/CSS that Rails scaffolds generate.
Diffstat (limited to 'guides/source/active_record_validations.md')
-rw-r--r--guides/source/active_record_validations.md689
1 files changed, 342 insertions, 347 deletions
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index 541b1a1e84..e752c6f3f9 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -6,34 +6,76 @@ the database using Active Record's validations feature.
After reading this guide, you will know:
-* Understand the life cycle of Active Record objects.
-* Use the built-in Active Record validation helpers.
-* Create your own custom validation methods.
-* Work with the error messages generated by the validation process.
-* Create callback methods that respond to events in the object life cycle.
-* Create special classes that encapsulate common behavior for your callbacks.
+* Use the built-in Active Record validation helpers
+* Create your own custom validation methods
+* Work with the error messages generated by the validation process
--------------------------------------------------------------------------------
Validations Overview
--------------------
-Before you dive into the detail of validations in Rails, you should understand a bit about how validations fit into the big picture.
+Here's an example of a very simple validation:
-### Why Use Validations?
+```ruby
+class Person < ActiveRecord::Base
+ validates :name, presence: true
+end
-Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address.
+Person.create(name: "John Doe").valid? # => true
+Person.create(name: nil).valid? # => false
+```
-There are several ways to validate data before it is saved into your database, including native database constraints, client-side validations, controller-level validations, and model-level validations:
+As you can see, our validation lets us know that our `Person` is not valid
+without a `name` attribute. The second `Person` will not be persisted to the
+database.
-* Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise.
-* Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user's browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site.
-* Controller-level validations can be tempting to use, but often become unwieldy and difficult to test and maintain. Whenever possible, it's a good idea to [keep your controllers skinny](http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model), as it will make your application a pleasure to work with in the long run.
-* Model-level validations are the best way to ensure that only valid data is saved into your database. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain. Rails makes them easy to use, provides built-in helpers for common needs, and allows you to create your own validation methods as well.
+Before we dig into more details, let's talk about how validations fit into the
+big picture of your application.
+
+### Why Use Validations?
+
+Validations are used to ensure that only valid data is saved into your
+database. For example, it may be important to your application to ensure that
+every user provides a valid email address and mailing address. Model-level
+validations are the best way to ensure that only valid data is saved into your
+database. They are database agnostic, cannot be bypassed by end users, and are
+convenient to test and maintain. Rails makes them easy to use, provides
+built-in helpers for common needs, and allows you to create your own validation
+methods as well.
+
+There are several other ways to validate data before it is saved into your
+database, including native database constraints, client-side validations,
+controller-level validations. Here's a summary of the pros and cons:
+
+* Database constraints and/or stored procedures make the validation mechanisms
+ database-dependent and can make testing and maintenance more difficult.
+ However, if your database is used by other applications, it may be a good
+ idea to use some constraints at the database level. Additionally,
+ database-level validations can safely handle some things (such as uniqueness
+ in heavily-used tables) that can be difficult to implement otherwise.
+* Client-side validations can be useful, but are generally unreliable if used
+ alone. If they are implemented using JavaScript, they may be bypassed if
+ JavaScript is turned off in the user's browser. However, if combined with
+ other techniques, client-side validation can be a convenient way to provide
+ users with immediate feedback as they use your site.
+* Controller-level validations can be tempting to use, but often become
+ unwieldy and difficult to test and maintain. Whenever possible, it's a good
+ idea to keep your controllers skinny, as it will make your application a
+ pleasure to work with in the long run.
+
+Choose these in certain, specific cases. It's the opinion of the Rails team
+that model-level validations are the most appropriate in most circumstances.
### When Does Validation Happen?
-There are two kinds of Active Record objects: those that correspond to a row inside your database and those that do not. When you create a fresh object, for example using the `new` method, that object does not belong to the database yet. Once you call `save` upon that object it will be saved into the appropriate database table. Active Record uses the `new_record?` instance method to determine whether an object is already in the database or not. Consider the following simple Active Record class:
+There are two kinds of Active Record objects: those that correspond to a row
+inside your database and those that do not. When you create a fresh object, for
+example using the `new` method, that object does not belong to the database
+yet. Once you call `save` upon that object it will be saved into the
+appropriate database table. Active Record uses the `new_record?` instance
+method to determine whether an object is already in the database or not.
+Consider the following simple Active Record class:
```ruby
class Person < ActiveRecord::Base
@@ -54,13 +96,21 @@ $ rails console
=> false
```
-TIP: All lines starting with a dollar sign `$` are intended to be run on the command line.
+Creating and saving a new record will send an SQL `INSERT` operation to the
+database. Updating an existing record will send an SQL `UPDATE` operation
+instead. Validations are typically run before these commands are sent to the
+database. If any validations fail, the object will be marked as invalid and
+Active Record will not perform the `INSERT` or `UPDATE` operation. This avoids
+storing an invalid object in the database. You can choose to have specific
+validations run when an object is created, saved, or updated.
-Creating and saving a new record will send an SQL `INSERT` operation to the database. Updating an existing record will send an SQL `UPDATE` operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the `INSERT` or `UPDATE` operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.
+CAUTION: There are many ways to change the state of an object in the database.
+Some methods will trigger validations, but some will not. This means that it's
+possible to save an object in the database in an invalid state if you aren't
+careful.
-CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful.
-
-The following methods trigger validations, and will save the object to the database only if the object is valid:
+The following methods trigger validations, and will save the object to the
+database only if the object is valid:
* `create`
* `create!`
@@ -70,11 +120,14 @@ The following methods trigger validations, and will save the object to the datab
* `update_attributes`
* `update_attributes!`
-The bang versions (e.g. `save!`) raise an exception if the record is invalid. The non-bang versions don't: `save` and `update_attributes` return `false`, `create` and `update` just return the objects.
+The bang versions (e.g. `save!`) raise an exception if the record is invalid.
+The non-bang versions don't: `save` and `update_attributes` return `false`,
+`create` and `update` just return the objects.
### Skipping Validations
-The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution.
+The following methods skip validations, and will save the object to the
+database regardless of its validity. They should be used with caution.
* `decrement!`
* `decrement_counter`
@@ -88,13 +141,17 @@ The following methods skip validations, and will save the object to the database
* `update_columns`
* `update_counters`
-Note that `save` also has the ability to skip validations if passed `validate: false` as argument. This technique should be used with caution.
+Note that `save` also has the ability to skip validations if passed `validate:
+false` as argument. This technique should be used with caution.
* `save(validate: false)`
### `valid?` and `invalid?`
-To verify whether or not an object is valid, Rails uses the `valid?` method. You can also use this method on your own. `valid?` triggers your validations and returns true if no errors were found in the object, and false otherwise.
+To verify whether or not an object is valid, Rails uses the `valid?` method.
+You can also use this method on your own. `valid?` triggers your validations
+and returns true if no errors were found in the object, and false otherwise.
+As you saw above:
```ruby
class Person < ActiveRecord::Base
@@ -105,9 +162,13 @@ Person.create(name: "John Doe").valid? # => true
Person.create(name: nil).valid? # => false
```
-After Active Record has performed validations, any errors found can be accessed through the `errors` instance method, which returns a collection of errors. By definition, an object is valid if this collection is empty after running validations.
+After Active Record has performed validations, any errors found can be accessed
+through the `errors` instance method, which returns a collection of errors. By
+definition, an object is valid if this collection is empty after running
+validations.
-Note that an object instantiated with `new` will not report errors even if it's technically invalid, because validations are not run when using `new`.
+Note that an object instantiated with `new` will not report errors even if it's
+technically invalid, because validations are not run when using `new`.
```ruby
class Person < ActiveRecord::Base
@@ -139,13 +200,21 @@ end
#=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
```
-`invalid?` is simply the inverse of `valid?`. It triggers your validations, returning true if any errors were found in the object, and false otherwise.
+`invalid?` is simply the inverse of `valid?`. It triggers your validations,
+returning true if any errors were found in the object, and false otherwise.
### `errors[]`
-To verify whether or not a particular attribute of an object is valid, you can use `errors[:attribute]`. It returns an array of all the errors for `:attribute`. If there are no errors on the specified attribute, an empty array is returned.
+To verify whether or not a particular attribute of an object is valid, you can
+use `errors[:attribute]`. It returns an array of all the errors for
+`:attribute`. If there are no errors on the specified attribute, an empty array
+is returned.
-This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the `ActiveRecord::Base#invalid?` method explained above because it doesn't verify the validity of the object as a whole. It only checks to see whether there are errors found on an individual attribute of the object.
+This method is only useful _after_ validations have been run, because it only
+inspects the errors collection and does not trigger validations itself. It's
+different from the `ActiveRecord::Base#invalid?` method explained above because
+it doesn't verify the validity of the object as a whole. It only checks to see
+whether there are errors found on an individual attribute of the object.
```ruby
class Person < ActiveRecord::Base
@@ -156,20 +225,38 @@ end
>> Person.create.errors[:name].any? # => true
```
-We'll cover validation errors in greater depth in the [Working with Validation Errors](#working-with-validation-errors) section. For now, let's turn to the built-in validation helpers that Rails provides by default.
+We'll cover validation errors in greater depth in the [Working with Validation
+Errors](#working-with-validation-errors) section. For now, let's turn to the
+built-in validation helpers that Rails provides by default.
Validation Helpers
------------------
-Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. Every time a validation fails, an error message is added to the object's `errors` collection, and this message is associated with the attribute being validated.
+Active Record offers many pre-defined validation helpers that you can use
+directly inside your class definitions. These helpers provide common validation
+rules. Every time a validation fails, an error message is added to the object's
+`errors` collection, and this message is associated with the attribute being
+validated.
-Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes.
+Each helper accepts an arbitrary number of attribute names, so with a single
+line of code you can add the same kind of validation to several attributes.
-All of them accept the `:on` and `:message` options, which define when the validation should be run and what message should be added to the `errors` collection if it fails, respectively. The `:on` option takes one of the values `:save` (the default), `:create` or `:update`. There is a default error message for each one of the validation helpers. These messages are used when the `:message` option isn't specified. Let's take a look at each one of the available helpers.
+All of them accept the `:on` and `:message` options, which define when the
+validation should be run and what message should be added to the `errors`
+collection if it fails, respectively. The `:on` option takes one of the values
+`:save` (the default), `:create` or `:update`. There is a default error
+message for each one of the validation helpers. These messages are used when
+the `:message` option isn't specified. Let's take a look at each one of the
+available helpers.
### `acceptance`
-Validates that a checkbox on the user interface was checked when a form was submitted. This is typically used when the user needs to agree to your application's terms of service, confirm reading some text, or any similar concept. This validation is very specific to web applications and this 'acceptance' does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute).
+This method validates that a checkbox on the user interface was checked when a
+form was submitted. This is typically used when the user needs to agree to your
+application's terms of service, confirm reading some text, or any similar
+concept. This validation is very specific to web applications and this
+'acceptance' does not need to be recorded anywhere in your database (if you
+don't have a field for it, the helper will just create a virtual attribute).
```ruby
class Person < ActiveRecord::Base
@@ -179,7 +266,8 @@ end
The default error message for this helper is "_must be accepted_".
-It can receive an `:accept` option, which determines the value that will be considered acceptance. It defaults to "1" and can be easily changed.
+It can receive an `:accept` option, which determines the value that will be
+considered acceptance. It defaults to "1" and can be easily changed.
```ruby
class Person < ActiveRecord::Base
@@ -189,7 +277,9 @@ end
### `validates_associated`
-You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, `valid?` will be called upon each one of the associated objects.
+You should use this helper when your model has associations with other models
+and they also need to be validated. When you try to save your object, `valid?`
+will be called upon each one of the associated objects.
```ruby
class Library < ActiveRecord::Base
@@ -200,13 +290,19 @@ end
This validation will work with all of the association types.
-CAUTION: Don't use `validates_associated` on both ends of your associations. They would call each other in an infinite loop.
+CAUTION: Don't use `validates_associated` on both ends of your associations.
+They would call each other in an infinite loop.
-The default error message for `validates_associated` is "_is invalid_". Note that each associated object will contain its own `errors` collection; errors do not bubble up to the calling model.
+The default error message for `validates_associated` is "_is invalid_". Note
+that each associated object will contain its own `errors` collection; errors do
+not bubble up to the calling model.
### `confirmation`
-You should use this helper when you have two text fields that should receive exactly the same content. For example, you may want to confirm an email address or a password. This validation creates a virtual attribute whose name is the name of the field that has to be confirmed with "_confirmation" appended.
+You should use this helper when you have two text fields that should receive
+exactly the same content. For example, you may want to confirm an email address
+or a password. This validation creates a virtual attribute whose name is the
+name of the field that has to be confirmed with "_confirmation" appended.
```ruby
class Person < ActiveRecord::Base
@@ -221,7 +317,9 @@ In your view template you could use something like
<%= text_field :person, :email_confirmation %>
```
-This check is performed only if `email_confirmation` is not `nil`. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at `presence` later on this guide):
+This check is performed only if `email_confirmation` is not `nil`. To require
+confirmation, make sure to add a presence check for the confirmation attribute
+(we'll take a look at `presence` later on this guide):
```ruby
class Person < ActiveRecord::Base
@@ -234,7 +332,8 @@ The default error message for this helper is "_doesn't match confirmation_".
### `exclusion`
-This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.
+This helper validates that the attributes' values are not included in a given
+set. In fact, this set can be any enumerable object.
```ruby
class Account < ActiveRecord::Base
@@ -243,13 +342,18 @@ class Account < ActiveRecord::Base
end
```
-The `exclusion` helper has an option `:in` that receives the set of values that will not be accepted for the validated attributes. The `:in` option has an alias called `:within` that you can use for the same purpose, if you'd like to. This example uses the `:message` option to show how you can include the attribute's value.
+The `exclusion` helper has an option `:in` that receives the set of values that
+will not be accepted for the validated attributes. The `:in` option has an
+alias called `:within` that you can use for the same purpose, if you'd like to.
+This example uses the `:message` option to show how you can include the
+attribute's value.
The default error message is "_is reserved_".
### `format`
-This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the `:with` option.
+This helper validates the attributes' values by testing whether they match a
+given regular expression, which is specified using the `:with` option.
```ruby
class Product < ActiveRecord::Base
@@ -262,7 +366,8 @@ The default error message is "_is invalid_".
### `inclusion`
-This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.
+This helper validates that the attributes' values are included in a given set.
+In fact, this set can be any enumerable object.
```ruby
class Coffee < ActiveRecord::Base
@@ -271,13 +376,17 @@ class Coffee < ActiveRecord::Base
end
```
-The `inclusion` helper has an option `:in` that receives the set of values that will be accepted. The `:in` option has an alias called `:within` that you can use for the same purpose, if you'd like to. The previous example uses the `:message` option to show how you can include the attribute's value.
+The `inclusion` helper has an option `:in` that receives the set of values that
+will be accepted. The `:in` option has an alias called `:within` that you can
+use for the same purpose, if you'd like to. The previous example uses the
+`:message` option to show how you can include the attribute's value.
The default error message for this helper is "_is not included in the list_".
### `length`
-This helper validates the length of the attributes' values. It provides a variety of options, so you can specify length constraints in different ways:
+This helper validates the length of the attributes' values. It provides a
+variety of options, so you can specify length constraints in different ways:
```ruby
class Person < ActiveRecord::Base
@@ -292,10 +401,15 @@ The possible length constraint options are:
* `:minimum` - The attribute cannot have less than the specified length.
* `:maximum` - The attribute cannot have more than the specified length.
-* `:in` (or `:within`) - The attribute length must be included in a given interval. The value for this option must be a range.
+* `:in` (or `:within`) - The attribute length must be included in a given
+ interval. The value for this option must be a range.
* `:is` - The attribute length must be equal to the given value.
-The default error messages depend on the type of length validation being performed. You can personalize these messages using the `:wrong_length`, `:too_long`, and `:too_short` options and `%{count}` as a placeholder for the number corresponding to the length constraint being used. You can still use the `:message` option to specify an error message.
+The default error messages depend on the type of length validation being
+performed. You can personalize these messages using the `:wrong_length`,
+`:too_long`, and `:too_short` options and `%{count}` as a placeholder for the
+number corresponding to the length constraint being used. You can still use the
+`:message` option to specify an error message.
```ruby
class Person < ActiveRecord::Base
@@ -304,7 +418,8 @@ class Person < ActiveRecord::Base
end
```
-This helper counts characters by default, but you can split the value in a different way using the `:tokenizer` option:
+This helper counts characters by default, but you can split the value in a
+different way using the `:tokenizer` option:
```ruby
class Essay < ActiveRecord::Base
@@ -318,13 +433,20 @@ class Essay < ActiveRecord::Base
end
```
-Note that the default error messages are plural (e.g., "is too short (minimum is %{count} characters)"). For this reason, when `:minimum` is 1 you should provide a personalized message or use `validates_presence_of` instead. When `:in` or `:within` have a lower limit of 1, you should either provide a personalized message or call `presence` prior to `length`.
+Note that the default error messages are plural (e.g., "is too short (minimum
+is %{count} characters)"). For this reason, when `:minimum` is 1 you should
+provide a personalized message or use `validates_presence_of` instead. When
+`:in` or `:within` have a lower limit of 1, you should either provide a
+personalized message or call `presence` prior to `length`.
The `size` helper is an alias for `length`.
### `numericality`
-This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by an integral or floating point number. To specify that only integral numbers are allowed set `:only_integer` to true.
+This helper validates that your attributes have only numeric values. By
+default, it will match an optional sign followed by an integral or floating
+point number. To specify that only integral numbers are allowed set
+`:only_integer` to true.
If you set `:only_integer` to `true`, then it will use the
@@ -332,9 +454,11 @@ If you set `:only_integer` to `true`, then it will use the
/\A[+-]?\d+\Z/
```
-regular expression to validate the attribute's value. Otherwise, it will try to convert the value to a number using `Float`.
+regular expression to validate the attribute's value. Otherwise, it will try to
+convert the value to a number using `Float`.
-WARNING. Note that the regular expression above allows a trailing newline character.
+WARNING. Note that the regular expression above allows a trailing newline
+character.
```ruby
class Player < ActiveRecord::Base
@@ -343,21 +467,34 @@ class Player < ActiveRecord::Base
end
```
-Besides `:only_integer`, this helper also accepts the following options to add constraints to acceptable values:
-
-* `:greater_than` - Specifies the value must be greater than the supplied value. The default error message for this option is "_must be greater than %{count}_".
-* `:greater_than_or_equal_to` - Specifies the value must be greater than or equal to the supplied value. The default error message for this option is "_must be greater than or equal to %{count}_".
-* `:equal_to` - Specifies the value must be equal to the supplied value. The default error message for this option is "_must be equal to %{count}_".
-* `:less_than` - Specifies the value must be less than the supplied value. The default error message for this option is "_must be less than %{count}_".
-* `:less_than_or_equal_to` - Specifies the value must be less than or equal the supplied value. The default error message for this option is "_must be less than or equal to %{count}_".
-* `:odd` - Specifies the value must be an odd number if set to true. The default error message for this option is "_must be odd_".
-* `:even` - Specifies the value must be an even number if set to true. The default error message for this option is "_must be even_".
+Besides `:only_integer`, this helper also accepts the following options to add
+constraints to acceptable values:
+
+* `:greater_than` - Specifies the value must be greater than the supplied
+ value. The default error message for this option is "_must be greater than
+ %{count}_".
+* `:greater_than_or_equal_to` - Specifies the value must be greater than or
+ equal to the supplied value. The default error message for this option is
+ "_must be greater than or equal to %{count}_".
+* `:equal_to` - Specifies the value must be equal to the supplied value. The
+ default error message for this option is "_must be equal to %{count}_".
+* `:less_than` - Specifies the value must be less than the supplied value. The
+ default error message for this option is "_must be less than %{count}_".
+* `:less_than_or_equal_to` - Specifies the value must be less than or equal the
+ supplied value. The default error message for this option is "_must be less
+ than or equal to %{count}_".
+* `:odd` - Specifies the value must be an odd number if set to true. The
+ default error message for this option is "_must be odd_".
+* `:even` - Specifies the value must be an even number if set to true. The
+ default error message for this option is "_must be even_".
The default error message is "_is not a number_".
### `presence`
-This helper validates that the specified attributes are not empty. It uses the `blank?` method to check if the value is either `nil` or a blank string, that is, a string that is either empty or consists of whitespace.
+This helper validates that the specified attributes are not empty. It uses the
+`blank?` method to check if the value is either `nil` or a blank string, that
+is, a string that is either empty or consists of whitespace.
```ruby
class Person < ActiveRecord::Base
@@ -365,7 +502,9 @@ class Person < ActiveRecord::Base
end
```
-If you want to be sure that an association is present, you'll need to test the associated object itself, and not whether the foreign key used to map the association is present:
+If you want to be sure that an association is present, you'll need to test
+whether the foreign key used to map the association is present, and not the
+associated object itself.
```ruby
class LineItem < ActiveRecord::Base
@@ -382,15 +521,22 @@ class Order < ActiveRecord::Base
end
```
-If you validate the presence of an object associated via a `has_one` or `has_many` relationship, it will check that the object is neither `blank?` nor `marked_for_destruction?`.
+If you validate the presence of an object associated via a `has_one` or
+`has_many` relationship, it will check that the object is neither `blank?` nor
+`marked_for_destruction?`.
-Since `false.blank?` is true, if you want to validate the presence of a boolean field you should use `validates :field_name, inclusion: { in: [true, false] }`.
+Since `false.blank?` is true, if you want to validate the presence of a boolean
+field you should use `validates :field_name, inclusion: { in: [true, false] }`.
The default error message is "_can't be empty_".
### `uniqueness`
-This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create a unique index in your database.
+This helper validates that the attribute's value is unique right before the
+object gets saved. It does not create a uniqueness constraint in the database,
+so it may happen that two different database connections create two records
+with the same value for a column that you intend to be unique. To avoid that,
+you must create a unique index in your database.
```ruby
class Account < ActiveRecord::Base
@@ -398,9 +544,11 @@ class Account < ActiveRecord::Base
end
```
-The validation happens by performing an SQL query into the model's table, searching for an existing record with the same value in that attribute.
+The validation happens by performing an SQL query into the model's table,
+searching for an existing record with the same value in that attribute.
-There is a `:scope` option that you can use to specify other attributes that are used to limit the uniqueness check:
+There is a `:scope` option that you can use to specify other attributes that
+are used to limit the uniqueness check:
```ruby
class Holiday < ActiveRecord::Base
@@ -409,7 +557,9 @@ class Holiday < ActiveRecord::Base
end
```
-There is also a `:case_sensitive` option that you can use to define whether the uniqueness constraint will be case sensitive or not. This option defaults to true.
+There is also a `:case_sensitive` option that you can use to define whether the
+uniqueness constraint will be case sensitive or not. This option defaults to
+true.
```ruby
class Person < ActiveRecord::Base
@@ -417,7 +567,8 @@ class Person < ActiveRecord::Base
end
```
-WARNING. Note that some databases are configured to perform case-insensitive searches anyway.
+WARNING. Note that some databases are configured to perform case-insensitive
+searches anyway.
The default error message is "_has already been taken_".
@@ -439,13 +590,19 @@ class GoodnessValidator < ActiveModel::Validator
end
```
-NOTE: Errors added to `record.errors[:base]` relate to the state of the record as a whole, and not to a specific attribute.
+NOTE: Errors added to `record.errors[:base]` relate to the state of the record
+as a whole, and not to a specific attribute.
-The `validates_with` helper takes a class, or a list of classes to use for validation. There is no default error message for `validates_with`. You must manually add errors to the record's errors collection in the validator class.
+The `validates_with` helper takes a class, or a list of classes to use for
+validation. There is no default error message for `validates_with`. You must
+manually add errors to the record's errors collection in the validator class.
-To implement the validate method, you must have a `record` parameter defined, which is the record to be validated.
+To implement the validate method, you must have a `record` parameter defined,
+which is the record to be validated.
-Like all other validations, `validates_with` takes the `:if`, `:unless` and `:on` options. If you pass any other options, it will send those options to the validator class as `options`:
+Like all other validations, `validates_with` takes the `:if`, `:unless` and
+`:on` options. If you pass any other options, it will send those options to the
+validator class as `options`:
```ruby
class Person < ActiveRecord::Base
@@ -463,7 +620,10 @@ end
### `validates_each`
-This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to `validates_each` will be tested against it. In the following example, we don't want names and surnames to begin with lower case.
+This helper validates attributes against a block. It doesn't have a predefined
+validation function. You should create one using a block, and every attribute
+passed to `validates_each` will be tested against it. In the following example,
+we don't want names and surnames to begin with lower case.
```ruby
class Person < ActiveRecord::Base
@@ -473,7 +633,10 @@ class Person < ActiveRecord::Base
end
```
-The block receives the record, the attribute's name and the attribute's value. You can do anything you like to check for valid data within the block. If your validation fails, you should add an error message to the model, therefore making it invalid.
+The block receives the record, the attribute's name and the attribute's value.
+You can do anything you like to check for valid data within the block. If your
+validation fails, you should add an error message to the model, therefore
+making it invalid.
Common Validation Options
-------------------------
@@ -482,7 +645,8 @@ These are common validation options:
### `:allow_nil`
-The `:allow_nil` option skips the validation when the value being validated is `nil`.
+The `:allow_nil` option skips the validation when the value being validated is
+`nil`.
```ruby
class Coffee < ActiveRecord::Base
@@ -495,7 +659,9 @@ TIP: `:allow_nil` is ignored by the presence validator.
### `:allow_blank`
-The `:allow_blank` option is similar to the `:allow_nil` option. This option will let validation pass if the attribute's value is `blank?`, like `nil` or an empty string for example.
+The `:allow_blank` option is similar to the `:allow_nil` option. This option
+will let validation pass if the attribute's value is `blank?`, like `nil` or an
+empty string for example.
```ruby
class Topic < ActiveRecord::Base
@@ -510,11 +676,19 @@ TIP: `:allow_blank` is ignored by the presence validator.
### `:message`
-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.
+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.
### `:on`
-The `:on` option lets you specify when the validation should happen. The default behavior for all the built-in validation helpers is to be run on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use `on: :create` to run the validation only when a new record is created or `on: :update` to run the validation only when a record is updated.
+The `:on` option lets you specify when the validation should happen. The
+default behavior for all the built-in validation helpers is to be run on save
+(both when you're creating a new record and when you're updating it). If you
+want to change it, you can use `on: :create` to run the validation only when a
+new record is created or `on: :update` to run the validation only when a record
+is updated.
```ruby
class Person < ActiveRecord::Base
@@ -532,7 +706,8 @@ end
Strict Validations
------------------
-You can also specify validations to be strict and raise `ActiveModel::StrictValidationFailed` when the object is invalid.
+You can also specify validations to be strict and raise
+`ActiveModel::StrictValidationFailed` when the object is invalid.
```ruby
class Person < ActiveRecord::Base
@@ -555,11 +730,18 @@ Person.new.valid? #=> TokenGenerationException: Token can't be blank
Conditional Validation
----------------------
-Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the `:if` and `:unless` options, which can take a symbol, a string, a `Proc` or an `Array`. You may use the `:if` option when you want to specify when the validation **should** happen. If you want to specify when the validation **should not** happen, then you may use the `:unless` option.
+Sometimes it will make sense to validate an object only when a given predicate
+is satisfied. You can do that by using the `:if` and `:unless` options, which
+can take a symbol, a string, a `Proc` or an `Array`. You may use the `:if`
+option when you want to specify when the validation **should** happen. If you
+want to specify when the validation **should not** happen, then you may use the
+`:unless` option.
### Using a Symbol with `:if` and `:unless`
-You can associate the `:if` and `:unless` options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.
+You can associate the `:if` and `:unless` options with a symbol corresponding
+to the name of a method that will get called right before validation happens.
+This is the most commonly used option.
```ruby
class Order < ActiveRecord::Base
@@ -573,7 +755,9 @@ end
### Using a String with `:if` and `:unless`
-You can also use a string that will be evaluated using `eval` and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.
+You can also use a string that will be evaluated using `eval` and needs to
+contain valid Ruby code. You should use this option only when the string
+represents a really short condition.
```ruby
class Person < ActiveRecord::Base
@@ -583,7 +767,10 @@ end
### Using a Proc with `:if` and `:unless`
-Finally, it's possible to associate `:if` and `:unless` with a `Proc` object which will be called. Using a `Proc` object gives you the ability to write an inline condition instead of a separate method. This option is best suited for one-liners.
+Finally, it's possible to associate `:if` and `:unless` with a `Proc` object
+which will be called. Using a `Proc` object gives you the ability to write an
+inline condition instead of a separate method. This option is best suited for
+one-liners.
```ruby
class Account < ActiveRecord::Base
@@ -594,7 +781,8 @@ end
### Grouping conditional validations
-Sometimes it is useful to have multiple validations use one condition, it can be easily achieved using `with_options`.
+Sometimes it is useful to have multiple validations use one condition, it can
+be easily achieved using `with_options`.
```ruby
class User < ActiveRecord::Base
@@ -605,11 +793,14 @@ class User < ActiveRecord::Base
end
```
-All validations inside of `with_options` block will have automatically passed the condition `if: :is_admin?`
+All validations inside of `with_options` block will have automatically passed
+the condition `if: :is_admin?`
### Combining validation conditions
-On the other hand, when multiple conditions define whether or not a validation should happen, an `Array` can be used. Moreover, you can apply both `:if` and `:unless` to the same validation.
+On the other hand, when multiple conditions define whether or not a validation
+should happen, an `Array` can be used. Moreover, you can apply both `:if` and
+`:unless` to the same validation.
```ruby
class Computer < ActiveRecord::Base
@@ -619,16 +810,21 @@ class Computer < ActiveRecord::Base
end
```
-The validation only runs when all the `:if` conditions and none of the `:unless` conditions are evaluated to `true`.
+The validation only runs when all the `:if` conditions and none of the
+`:unless` conditions are evaluated to `true`.
Performing Custom Validations
-----------------------------
-When the built-in validation helpers are not enough for your needs, you can write your own validators or validation methods as you prefer.
+When the built-in validation helpers are not enough for your needs, you can
+write your own validators or validation methods as you prefer.
### Custom Validators
-Custom validators are classes that extend `ActiveModel::Validator`. These classes must implement a `validate` method which takes a record as an argument and performs the validation on it. The custom validator is called using the `validates_with` method.
+Custom validators are classes that extend `ActiveModel::Validator`. These
+classes must implement a `validate` method which takes a record as an argument
+and performs the validation on it. The custom validator is called using the
+`validates_with` method.
```ruby
class MyValidator < ActiveModel::Validator
@@ -645,7 +841,12 @@ class Person
end
```
-The easiest way to add custom validators for validating individual attributes is with the convenient `ActiveModel::EachValidator`. In this case, the custom validator class must implement a `validate_each` method which takes three arguments: record, attribute and value which correspond to the instance, the attribute to be validated and the value of the attribute in the passed instance.
+The easiest way to add custom validators for validating individual attributes
+is with the convenient `ActiveModel::EachValidator`. In this case, the custom
+validator class must implement a `validate_each` method which takes three
+arguments: record, attribute and value which correspond to the instance, the
+attribute to be validated and the value of the attribute in the passed
+instance.
```ruby
class EmailValidator < ActiveModel::EachValidator
@@ -661,13 +862,18 @@ class Person < ActiveRecord::Base
end
```
-As shown in the example, you can also combine standard validations with your own custom validators.
+As shown in the example, you can also combine standard validations with your
+own custom validators.
### Custom Methods
-You can also create methods that verify the state of your models and add messages to the `errors` collection when they are invalid. You must then register these methods by using the `validate` class method, passing in the symbols for the validation methods' names.
+You can also create methods that verify the state of your models and add
+messages to the `errors` collection when they are invalid. You must then
+register these methods by using the `validate` class method, passing in the
+symbols for the validation methods' names.
-You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.
+You can pass more than one symbol for each class method and the respective
+validations will be run in the same order as they were registered.
```ruby
class Invoice < ActiveRecord::Base
@@ -688,7 +894,9 @@ class Invoice < ActiveRecord::Base
end
```
-By default such validations will run every time you call `valid?`. It is also possible to control when to run these custom validations by giving an `:on` option to the `validate` method, with either: `:create` or `:update`.
+By default such validations will run every time you call `valid?`. It is also
+possible to control when to run these custom validations by giving an `:on`
+option to the `validate` method, with either: `:create` or `:update`.
```ruby
class Invoice < ActiveRecord::Base
@@ -700,269 +908,56 @@ class Invoice < ActiveRecord::Base
end
```
-You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find it useful to express that a certain field corresponds to a set of choices:
+Displaying Validation Errors in Views
+-------------------------------------
-```ruby
-ActiveRecord::Base.class_eval do
- def self.validates_as_choice(attr_name, n, options={})
- validates attr_name, inclusion: { { in: 1..n }.merge!(options) }
- end
-end
-```
+Once you've created a model and added validations, if that model is created via
+a web form, you probably want to display an error message when one of the
+validations fail.
-Simply reopen `ActiveRecord::Base` and define a class method like that. You'd typically put this code somewhere in `config/initializers`. You can use this helper like this:
+Because every application handles this kind of thing differently, Rails does
+not include any view helpers to help you generate these messages directly.
+However, due to the rich number of methods Rails gives you to interact with
+validations in general, it's fairly easy to build your own. In addition, when
+generating a scaffold, Rails will put some ERB into the `_form.html.erb` that
+it generates that displays the full list of errors on that model.
-```ruby
-class Movie < ActiveRecord::Base
- validates_as_choice :rating, 5
-end
-```
-
-Working with Validation Errors
-------------------------------
-
-In addition to the `valid?` and `invalid?` methods covered earlier, Rails provides a number of methods for working with the `errors` collection and inquiring about the validity of objects.
-
-The following is a list of the most commonly used methods. Please refer to the `ActiveModel::Errors` documentation for a list of all the available methods.
-
-### `errors`
-
-Returns an instance of the class `ActiveModel::Errors` containing all errors. Each key is the attribute name and the value is an array of strings with all errors.
+Assuming we have a model that's been saved in an instance variable named
+`@post`, it looks like this:
```ruby
-class Person < ActiveRecord::Base
- validates :name, presence: true, length: { minimum: 3 }
-end
-
-person = Person.new
-person.valid? # => false
-person.errors
- # => {:name=>["can't be blank", "is too short (minimum is 3 characters)"]}
-
-person = Person.new(name: "John Doe")
-person.valid? # => true
-person.errors # => []
-```
-
-### `errors[]`
-
-`errors[]` is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array.
+<% if @post.errors.any? %>
+ <div id="error_explanation">
+ <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
-```ruby
-class Person < ActiveRecord::Base
- validates :name, presence: true, length: { minimum: 3 }
-end
-
-person = Person.new(name: "John Doe")
-person.valid? # => true
-person.errors[:name] # => []
-
-person = Person.new(name: "JD")
-person.valid? # => false
-person.errors[:name] # => ["is too short (minimum is 3 characters)"]
-
-person = Person.new
-person.valid? # => false
-person.errors[:name]
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
-```
-
-### `errors.add`
-
-The `add` method lets you manually add messages that are related to particular attributes. You can use the `errors.full_messages` or `errors.to_a` methods to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). `add` receives the name of the attribute you want to add the message to, and the message itself.
-
-```ruby
-class Person < ActiveRecord::Base
- def a_method_used_for_validation_purposes
- errors.add(:name, "cannot contain the characters !@#%*()_-+=")
- end
-end
-
-person = Person.create(name: "!@#")
-
-person.errors[:name]
- # => ["cannot contain the characters !@#%*()_-+="]
-
-person.errors.full_messages
- # => ["Name cannot contain the characters !@#%*()_-+="]
-```
-
-Another way to do this is using `[]=` setter
-
-```ruby
- class Person < ActiveRecord::Base
- def a_method_used_for_validation_purposes
- errors[:name] = "cannot contain the characters !@#%*()_-+="
- end
- end
-
- person = Person.create(name: "!@#")
-
- person.errors[:name]
- # => ["cannot contain the characters !@#%*()_-+="]
-
- person.errors.to_a
- # => ["Name cannot contain the characters !@#%*()_-+="]
-```
-
-### `errors[:base]`
-
-You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since `errors[:base]` is an array, you can simply add a string to it and it will be used as an error message.
-
-```ruby
-class Person < ActiveRecord::Base
- def a_method_used_for_validation_purposes
- errors[:base] << "This person is invalid because ..."
- end
-end
-```
-
-### `errors.clear`
-
-The `clear` method is used when you intentionally want to clear all the messages in the `errors` collection. Of course, calling `errors.clear` upon an invalid object won't actually make it valid: the `errors` collection will now be empty, but the next time you call `valid?` or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the `errors` collection will be filled again.
-
-```ruby
-class Person < ActiveRecord::Base
- validates :name, presence: true, length: { minimum: 3 }
-end
-
-person = Person.new
-person.valid? # => false
-person.errors[:name]
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
-
-person.errors.clear
-person.errors.empty? # => true
-
-p.save # => false
-
-p.errors[:name]
-# => ["can't be blank", "is too short (minimum is 3 characters)"]
-```
-
-### `errors.size`
-
-The `size` method returns the total number of error messages for the object.
-
-```ruby
-class Person < ActiveRecord::Base
- validates :name, presence: true, length: { minimum: 3 }
-end
-
-person = Person.new
-person.valid? # => false
-person.errors.size # => 2
-
-person = Person.new(name: "Andrea", email: "andrea@example.com")
-person.valid? # => true
-person.errors.size # => 0
-```
-
-Displaying Validation Errors in the View
-----------------------------------------
-
-[DynamicForm](https://github.com/joelmoss/dynamic_form) provides helpers to display the error messages of your models in your view templates.
-
-You can install it as a gem by adding this line to your Gemfile:
-
-```ruby
-gem "dynamic_form"
-```
-
-Now you will have access to the two helper methods `error_messages` and `error_messages_for` in your view templates.
-
-### `error_messages` and `error_messages_for`
-
-When creating a form with the `form_for` helper, you can use the `error_messages` method on the form builder to render all failed validation messages for the current model instance.
-
-```ruby
-class Product < ActiveRecord::Base
- validates :description, :value, presence: true
- validates :value, numericality: true, allow_nil: true
-end
-```
-
-```erb
-<%= form_for(@product) do |f| %>
- <%= f.error_messages %>
- <p>
- <%= f.label :description %><br />
- <%= f.text_field :description %>
- </p>
- <p>
- <%= f.label :value %><br />
- <%= f.text_field :value %>
- </p>
- <p>
- <%= f.submit "Create" %>
- </p>
+ <ul>
+ <% @post.errors.full_messages.each do |msg| %>
+ <li><%= msg %></li>
+ <% end %>
+ </ul>
+ </div>
<% end %>
```
-If you submit the form with empty fields, the result will be similar to the one shown below:
-
-![Error messages](images/error_messages.png)
+Furthermore, if you use the Rails form helpers to generate your forms, when
+a validation error occurs on a field, it will generate an extra `<div>` around
+the entry.
-NOTE: The appearance of the generated HTML will be different from the one shown, unless you have used scaffolding. See [Customizing the Error Messages CSS](#customizing-the-error-messages-css).
-
-You can also use the `error_messages_for` helper to display the error messages of a model assigned to a view template. It is very similar to the previous example and will achieve exactly the same result.
-
-```erb
-<%= error_messages_for :product %>
```
-
-The displayed text for each error message will always be formed by the capitalized name of the attribute that holds the error, followed by the error message itself.
-
-Both the `form.error_messages` and the `error_messages_for` helpers accept options that let you customize the `div` element that holds the messages, change the header text, change the message below the header, and specify the tag used for the header element. For example,
-
-```erb
-<%= f.error_messages header_message: "Invalid product!",
- message: "You'll need to fix the following fields:",
- header_tag: :h3 %>
+<div class="field_with_errors">
+ <input id="post_title" name="post[title]" size="30" type="text" value="">
+</div>
```
-results in:
-
-![Customized error messages](images/customized_error_messages.png)
+You can then style this div however you'd like. The default scaffold that
+Rails generates, for example, adds this CSS rule:
-If you pass `nil` in any of these options, the corresponding section of the `div` will be discarded.
-
-### Customizing the Error Messages CSS
-
-The selectors used to customize the style of error messages are:
-
-* `.field_with_errors` - Style for the form fields and labels with errors.
-* `#error_explanation` - Style for the `div` element with the error messages.
-* `#error_explanation h2` - Style for the header of the `div` element.
-* `#error_explanation p` - Style for the paragraph holding the message that appears right below the header of the `div` element.
-* `#error_explanation ul li` - Style for the list items with individual error messages.
-
-If scaffolding was used, file `app/assets/stylesheets/scaffolds.css.scss` will have been generated automatically. This file defines the red-based styles you saw in the examples above.
-
-The name of the class and the id can be changed with the `:class` and `:id` options, accepted by both helpers.
-
-### Customizing the Error Messages HTML
-
-By default, form fields with errors are displayed enclosed by a `div` element with the `field_with_errors` CSS class. However, it's possible to override that.
-
-The way form fields with errors are treated is defined by `ActionView::Base.field_error_proc`. This is a `Proc` that receives two parameters:
-
-* A string with the HTML tag
-* An instance of `ActionView::Helpers::InstanceTag`.
-
-Below is a simple example where we change the Rails behavior to always display the error messages in front of each of the form fields in error. The error messages will be enclosed by a `span` element with a `validation-error` CSS class. There will be no `div` element enclosing the `input` element, so we get rid of that red border around the text field. You can use the `validation-error` CSS class to style it anyway you want.
-
-```ruby
-ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
- if html_tag =~ /\<label/
- html_tag
- else
- errors = Array(instance.error_message).join(',')
- %(#{html_tag}<span class="validation-error">&nbsp;#{errors}</span>).html_safe
- end
-end
+```
+.field_with_errors {
+ padding: 2px;
+ background-color: red;
+ display: table;
+}
```
-The result looks like the following:
-
-![Validation error messages](images/validation_error_messages.png)
+This means that any field with an error ends up with a 2 pixel red border.