From fbfc54efddc803e68e234ebcf1fbeccea042f879 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Mon, 12 Jan 2009 17:17:44 -0600 Subject: Edits to validation section --- .../source/activerecord_validations_callbacks.txt | 102 +++++++++++---------- 1 file changed, 52 insertions(+), 50 deletions(-) (limited to 'railties/doc/guides/source/activerecord_validations_callbacks.txt') diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt index 4dc0fdb236..8393d183e9 100644 --- a/railties/doc/guides/source/activerecord_validations_callbacks.txt +++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt @@ -1,32 +1,34 @@ Active Record Validations and Callbacks ======================================= -This guide teaches you how to work with the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database and also how to teach them to perform custom operations at certain points of their lifecycles. +This guide teaches you how to hook into the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database as well as how to perform custom operations at certain points in the object lifecycle. After reading this guide and trying out the presented concepts, we hope that you'll be able to: -* Correctly use all the built-in Active Record validation helpers +* Use the built-in Active Record validation helpers * Create your own custom validation methods * Work with the error messages generated by the validation process -* Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved. -* Create special classes that encapsulate common behaviour for your callbacks -* Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations. +* Create callback methods to respond to events in the object lifecycle. +* Create special classes that encapsulate common behavior for your callbacks +* Create Rails Observers -== Motivations to validate your Active Record objects +== Overview of ActiveRecord Validation -The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly. +Before you dive into the detail of validations in Rails, you should understand a bit about how validations fit into the big picture. Why should you use validations? When do these validations take place? + +=== Why Use ActiveRecord Validations? -There are several ways to validate the data that goes to the database, like using database native constraints, implementing validations only at the client side or implementing them directly into your models. Each one has pros and cons: +The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly. -* Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and mantain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level. -* Implementing validations only at the client side can be problematic, specially with web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data. -* Using validation directly into your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the hability to easily create validations, using several built-in helpers while still allowing you to create your own validation methods. +There are several ways that you could validate the data that goes to the database, including native database constraints, client-side validations, and model-level validations. Each of these has pros and cons: -== How it works +* Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and maintain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that are problematic to implement from the application level. +* Implementing validations only at the client side can be difficult in web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data. +* Using validation directly in your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the ability to easily create validations, providing built-in helpers for common validations while still allowing you to create your own validation methods. -=== When does validation happen? +=== When Does Validation Happen? -There are two kinds of Active Record objects: those that correspond to a row inside your database and those who do not. When you create a fresh object, using the +new+ method, that object does not belong to the database yet. Once you call +save+ upon that object it'll be recorded to it's table. Active Record uses the +new_record?+ instance method to discover if an object is already in the database or not. Consider the following simple and very creative 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, 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: [source, ruby] ------------------------------------------------------------------ @@ -34,7 +36,7 @@ class Person < ActiveRecord::Base end ------------------------------------------------------------------ -We can see how it works by looking at the following script/console output: +We can see how it works by looking at some script/console output: ------------------------------------------------------------------ >> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979")) @@ -47,25 +49,25 @@ We can see how it works by looking at the following script/console output: => false ------------------------------------------------------------------ -Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL update operation. Active Record will use these facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one. +Saving new records means sending an SQL +INSERT+ operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL +UPDATE+ operation. Active Record will use these facts to perform validations upon your objects, keeping them out of the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one. -CAUTION: There are four methods that when called will trigger validation: +save+, +save!+, +update_attributes+ and +update_attributes!+. There is one method left, which is +update_attribute+. This method will update the value of an attribute without triggering any validation, so be careful when using +update_attribute+, since it can let you save your objects in an invalid state. +CAUTION: There are four methods that when called will trigger validation: +save+, +save!+, +update_attributes+ and +update_attributes!+. There is one update method for Active Record objects left, which is +update_attribute+. This method will update the value of an attribute _without_ triggering any validation. Be careful when using +update_attribute+, because it can let you save your objects in an invalid state. -=== The meaning of 'valid' +=== The Meaning of +valid+ -For verifying if an object is valid, Active Record uses the +valid?+ method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the +errors+ instance method. The proccess is really simple: If the +errors+ method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the +errors+ collection. +To verify whether an object is valid, Active Record uses the +valid?+ method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the +errors+ instance method. The process is really simple: If the +errors+ method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the +errors+ collection. -== The declarative validation helpers +== The Declarative Validation Helpers -Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validations rules that are commonly used in most of the applications that you'll write, so you don't need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object's +errors+ collection, this message being associated with the field being validated. +Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validation rules that are commonly used. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the field being validated. -Each helper accepts an arbitrary number of attributes, received as symbols, 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 attributes identified by symbols, so with a single line of code you can add the same kind of validation to several attributes. -All these helpers accept the +:on+ and +:message+ options, which define when the validation should be applied and what message should be added to the +errors+ collection when it fails, respectively. The +:on+ option takes one of the values +:save+ (it's 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 used. Let's take a look at each one of the available helpers, listed in alphabetic order. +All these helpers accept the +:on+ and +:message+ options, which define when the validation should be applied and what message should be added to the +errors+ collection when 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 used. Let's take a look at each one of the available helpers. === The +validates_acceptance_of+ helper -Validates that a checkbox has been checked for agreement purposes. It's normally used when the user needs to agree with your application's terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually 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). +Validates that a checkbox on the user interface was checked when a form was submitted. This is normally 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 actually 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). [source, ruby] ------------------------------------------------------------------ @@ -76,7 +78,7 @@ end The default error message for +validates_acceptance_of+ is "_must be accepted_" -+validates_acceptance_of+ can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it. ++validates_acceptance_of+ can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1", but you can change this. [source, ruby] ------------------------------------------------------------------ @@ -85,7 +87,6 @@ class Person < ActiveRecord::Base end ------------------------------------------------------------------ - === The +validates_associated+ helper 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. @@ -100,13 +101,13 @@ end This validation will work with all the association types. -CAUTION: Pay attention not to use +validates_associated+ on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack. +CAUTION: Don't use +validates_associated+ on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack. -The default error message for +validates_associated+ is "_is invalid_". Note that the errors for each failed validation in the associated objects will be set there and not in this 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. === The +validates_confirmation_of+ helper -You should use this helper when you have two text fields that should receive exactly the same content, like when you want to confirm an email address or password. This validation creates a virtual attribute, using 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, using the name of the field that has to be confirmed with '_confirmation' appended. [source, ruby] ------------------------------------------------------------------ @@ -116,6 +117,7 @@ end ------------------------------------------------------------------ In your view template you could use something like +[source, html] ------------------------------------------------------------------ <%= text_field :person, :email %> <%= text_field :person, :email_confirmation %> @@ -145,13 +147,13 @@ class MovieFile < ActiveRecord::Base end ------------------------------------------------------------------ -The +validates_exclusion_of+ 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. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask. +The +validates_exclusion_of+ 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 personalize it with the current attribute's value, through the +%s+ format mask. The default error message for +validates_exclusion_of+ is "_is not included in the list_". === The +validates_format_of+ helper -This helper validates the attributes's values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the +:with+ option. +This helper validates the attributes' values by testing whether they match a given pattern. This pattern must be specified using a Ruby regular expression, which is specified using the +:with+ option. [source, ruby] ------------------------------------------------------------------ @@ -175,13 +177,13 @@ class Coffee < ActiveRecord::Base end ------------------------------------------------------------------ -The +validates_inclusion_of+ 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. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask. +The +validates_inclusion_of+ 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 personalize it with the current attribute's value, through the +%s+ format mask. The default error message for +validates_inclusion_of+ is "_is not included in the list_". === The +validates_length_of+ helper -This helper validates the length of your attribute's value. It can receive a variety of different options, so you can specify length contraints in different ways. +This helper validates the length of your attribute's value. It includes a variety of different options, so you can specify length constraints in different ways: [source, ruby] ------------------------------------------------------------------ @@ -200,7 +202,7 @@ The possible length constraint options are: * +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range. * +:is+ - The attribute length must be equal to a 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 the +%d+ format mask as a placeholder for the number corresponding to the length contraint 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 the +%d+ format mask 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. [source, ruby] ------------------------------------------------------------------ @@ -209,13 +211,13 @@ class Person < ActiveRecord::Base end ------------------------------------------------------------------ -This helper has an alias called +validates_size_of+, it's the same helper with a different name. You can use it if you'd like to. +The +validates_size_of+ helper is an alias for +validates_length_of+. === The +validates_numericality_of+ helper This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the +:integer_only+ option set to true, you can specify that only integral numbers are allowed. -If you use +:integer_only+ set 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 using +Kernel.Float+. +If you set +:integer_only+ 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 +Kernel.Float+. [source, ruby] ------------------------------------------------------------------ @@ -229,7 +231,7 @@ The default error message for +validates_numericality_of+ is "_is not a number_" === The +validates_presence_of+ helper -This helper validates that the attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty). +This helper validates that the specified attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty). [source, ruby] ------------------------------------------------------------------ @@ -238,7 +240,7 @@ class Person < ActiveRecord::Base end ------------------------------------------------------------------ -NOTE: If you want to be sure that an association is present, you'll need to test if the foreign key used to map the association is present, and not the associated object itself. +NOTE: 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. [source, ruby] ------------------------------------------------------------------ @@ -248,13 +250,13 @@ class LineItem < ActiveRecord::Base end ------------------------------------------------------------------ -NOTE: If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true +NOTE: If you want to validate the presence of a boolean field (where the real values are true and false), you should use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true The default error message for +validates_presence_of+ is "_can't be empty_". === The +validates_uniqueness_of+ helper -This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an 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 directly into your 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 an unique index in your database. [source, ruby] ------------------------------------------------------------------ @@ -265,7 +267,7 @@ end The validation happens by performing a SQL query into the model's table, searching for a record where the attribute that must be validated is equal to the value in the object being validated. -There is a +:scope+ option that you can use to specify other attributes that must be used to define uniqueness: +There is a +:scope+ option that you can use to specify other attributes that are used to limit the uniqueness check: [source, ruby] ------------------------------------------------------------------ @@ -275,7 +277,7 @@ class Holiday < ActiveRecord::Base end ------------------------------------------------------------------ -There is also a +:case_sensitive+ option that you can use to define if the uniqueness contraint 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. [source, ruby] ------------------------------------------------------------------ @@ -299,15 +301,15 @@ class Person < ActiveRecord::Base end ------------------------------------------------------------------ -The block receives the model, the attribute's name and the attribute's value. If your validation fails, you can add an error message to the model, therefore making it invalid. +The block receives the model, 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 can add an error message to the model, therefore making it invalid. -== Common validation options +== Common Validation Options -There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which we'll cover right at the next topic. +There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which are discussed later in the conditional validation topic. === The +:allow_nil+ option -You may use the +:allow_nil+ option everytime you want to trigger a validation only if the value being validated is not +nil+. You may be asking yourself if it makes any sense to use +:allow_nil+ and +validates_presence_of+ together. Well, it does. Remember, validation will be skipped only for +nil+ attributes, but empty strings are not considered +nil+. +The +:allow_nil+ option skips the validation when the value being validated is +nil+. You may be asking yourself if it makes any sense to use +:allow_nil+ and +validates_presence_of+ together. Well, it does. Remember, the validation will be skipped only for +nil+ attributes, but empty strings are not considered +nil+. [source, ruby] ------------------------------------------------------------------ @@ -319,7 +321,7 @@ end === The +:allow_blank+ option -In compliment to +:allow_nil+ we have +:allow_blank+. This option will let validation pass if the attribute's value is +nil+ or an empty string, i.e., any value that returns +true+ for +blank?+. +The +:allow_blank: option is similar to the +:allow_nil+ option. This option will let validation pass if the attribute's value is +nil+ or an empty string, i.e., any value that returns +true+ for +blank?+. [source, ruby] ------------------------------------------------------------------ @@ -333,11 +335,11 @@ Topic.create("title" => nil).valid? # => true === The +:message+ option -As stated before, 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, together with the attribute name. === The +:on+ option -As stated before, the +:on+ option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran 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 ran 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. [source, ruby] ------------------------------------------------------------------ @@ -348,7 +350,7 @@ class Person < ActiveRecord::Base # => it will be possible to create the record with a 'non-numerical age' validates_numericality_of :age, :on => :update - # => the default + # => the default (validates on both create and update) validates_presence_of :name, :on => :save end ------------------------------------------------------------------ -- cgit v1.2.3