mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Small improvements to Validations and Callbacks guide
This commit is contained in:
parent
a528eb19a6
commit
bc1c856b21
1 changed files with 31 additions and 37 deletions
|
@ -1,15 +1,15 @@
|
|||
h2. Active Record Validations and Callbacks
|
||||
|
||||
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.
|
||||
This guide teaches you how to hook into the lifecycle of your Active Record objects. You will learn how to validate the state of objects before they go into the database, and 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:
|
||||
|
||||
* 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 to respond to events in the object lifecycle.
|
||||
* Create callback methods that respond to events in the object lifecycle
|
||||
* Create special classes that encapsulate common behavior for your callbacks
|
||||
* Create Rails Observers
|
||||
* Create Observers
|
||||
|
||||
endprologue.
|
||||
|
||||
|
@ -17,22 +17,20 @@ endprologue.
|
|||
# http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
|
||||
# http://api.rubyonrails.org/classes/ActiveRecord/Base.html
|
||||
|
||||
h3. Overview of ActiveRecord Validation
|
||||
h3. 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. Why should you use validations? When do these validations take place?
|
||||
Before you dive into the detail of validations in Rails, you should understand a bit about how validations fit into the big picture.
|
||||
|
||||
h4. Why Use ActiveRecord Validations?
|
||||
h4. Why Use Validations?
|
||||
|
||||
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.
|
||||
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 and email address and valid postal code.
|
||||
|
||||
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:
|
||||
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.
|
||||
|
||||
* 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.
|
||||
|
||||
# TODO consider adding a bullet point on validations in controllers, and why model validations should be preferred over complicated controllers.
|
||||
# http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model
|
||||
* 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.
|
||||
|
||||
h4. When Does Validation Happen?
|
||||
|
||||
|
@ -47,7 +45,7 @@ We can see how it works by looking at some script/console output:
|
|||
|
||||
<shell>
|
||||
>> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979"))
|
||||
=> #<Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil>
|
||||
=> #<Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil>
|
||||
>> p.new_record?
|
||||
=> true
|
||||
>> p.save
|
||||
|
@ -140,7 +138,7 @@ end
|
|||
>> Person.create.errors.invalid?(:name) # => true
|
||||
</ruby>
|
||||
|
||||
h3. Declarative Validation Helpers
|
||||
h3. Validation Helpers
|
||||
|
||||
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.
|
||||
|
||||
|
@ -309,7 +307,6 @@ Besides +:only_integer+, the +validates_numericality_of+ helper also accepts the
|
|||
* +: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 for +validates_numericality_of+ is "_is not a number_".
|
||||
|
||||
h4. validates_presence_of
|
||||
|
@ -429,7 +426,7 @@ class Person < ActiveRecord::Base
|
|||
end
|
||||
</ruby>
|
||||
|
||||
h3. Conditional validation
|
||||
h3. 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 or a Ruby Proc. 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.
|
||||
|
||||
|
@ -468,7 +465,7 @@ class Account < ActiveRecord::Base
|
|||
end
|
||||
</ruby>
|
||||
|
||||
h3. Writing your own validation methods
|
||||
h3. Custom Validation Methods
|
||||
|
||||
When the built-in validation helpers are not enough for your needs, you can write your own validation methods. You can do that by implementing methods that verify the state of your models and add messages to their +errors+ collection when they are invalid. You must then register those methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, 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 ran in the same order as they were registered.
|
||||
|
||||
|
@ -514,9 +511,8 @@ class Person < ActiveRecord::Base
|
|||
end
|
||||
</ruby>
|
||||
|
||||
h3. Manipulating the errors collection
|
||||
h3. Validation Errors
|
||||
|
||||
# TODO consider renaming section to something more simple, like "Validation errors"
|
||||
# Consider combining with new section at the top with Object#valid? and Object#invalid?
|
||||
# Consider moving this stuff above the current 2-6 sections (e.g. save the validation details until after this?)
|
||||
|
||||
|
@ -599,7 +595,7 @@ p.errors.on(:name)
|
|||
# TODO consider discussing other methods (e.g. errors.size)
|
||||
# http://api.rubyonrails.org/classes/ActiveRecord/Errors.html
|
||||
|
||||
h3. Using error collection in views
|
||||
h3. Displaying Validation Errors the View
|
||||
|
||||
Rails provides built-in helpers to display the error messages of your models in your view templates. 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.
|
||||
|
||||
|
@ -659,7 +655,7 @@ It's also possible to change the CSS classes used by the +error_messages+ helper
|
|||
* +#errorExplanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element.
|
||||
* +#errorExplanation ul li+ - Style for the list of error messages.
|
||||
|
||||
h4. Changing the way form fields with errors are displayed
|
||||
h4. Changing the Way Form Fields with Errors are Displayed
|
||||
|
||||
By default, form fields with errors are displayed enclosed by a +div+ element with the +fieldWithErrors+ CSS class. However, we can write some Ruby code to override the way Rails treats those fields by default. Here is a simple example where we change the Rails behaviour to always display the error messages in front of each of the form fields with errors. 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.
|
||||
|
||||
|
@ -684,7 +680,7 @@ The way form fields with errors are treated is defined by the +ActionView::Base.
|
|||
* A string with the HTML tag
|
||||
* An object of the +ActionView::Helpers::InstanceTag+ class.
|
||||
|
||||
h3. Callbacks
|
||||
h3. Callbacks Overview
|
||||
|
||||
Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database.
|
||||
|
||||
|
@ -693,7 +689,7 @@ Callbacks are methods that get called at certain moments of an object's lifecycl
|
|||
# http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002220
|
||||
# http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
|
||||
|
||||
h4. Callback registration
|
||||
h4. Callback Registration
|
||||
|
||||
In order to use the available callbacks, you need to register them. You can do that by implementing them as an ordinary methods, and then using a macro-style class method to register then as callbacks.
|
||||
|
||||
|
@ -712,7 +708,7 @@ class User < ActiveRecord::Base
|
|||
end
|
||||
</ruby>
|
||||
|
||||
The macro-style class methods can also receive a block. Rails best practices say that you should only use this style of registration if the code inside your block is so short that it fits in just one line.
|
||||
The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in just one line.
|
||||
|
||||
<ruby>
|
||||
class User < ActiveRecord::Base
|
||||
|
@ -722,15 +718,13 @@ class User < ActiveRecord::Base
|
|||
end
|
||||
</ruby>
|
||||
|
||||
CAUTION: Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details.
|
||||
It's considered good practice to declare callback methods as being protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.
|
||||
|
||||
# TODO consider not making this a warning, just a note (this is an implementation detail, not a requirement of the library)
|
||||
|
||||
h3. Conditional callbacks
|
||||
h3. Conditional Callbacks
|
||||
|
||||
Like in validations, we can also make our callbacks conditional, calling then 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 or a Ruby Proc. You may use the +:if+ option when you want to specify when the callback *should* get called. If you want to specify when the callback *should not* be called, then you may use the +:unless+ option.
|
||||
|
||||
h4. Using a symbol with the :if and :unless
|
||||
h4. Using :if and :unless with a Symbol
|
||||
|
||||
You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before the callback. If this method returns +false+ the callback won't be executed. This is the most common option. Using this form of registration it's also possible to register several different methods that should be called to check the if the callback should be executed.
|
||||
|
||||
|
@ -740,7 +734,7 @@ class Order < ActiveRecord::Base
|
|||
end
|
||||
</ruby>
|
||||
|
||||
h4. Using a string with the :if and :unless
|
||||
h4. Using :if and :unless with a String
|
||||
|
||||
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.
|
||||
|
||||
|
@ -750,7 +744,7 @@ class Order < ActiveRecord::Base
|
|||
end
|
||||
</ruby>
|
||||
|
||||
h4. Using a Proc object with the :if and :unless
|
||||
h4. Using :if and :unless with a Proc
|
||||
|
||||
Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object. This option is best suited when writing short validation methods, usually one-liners.
|
||||
|
||||
|
@ -772,7 +766,7 @@ class Comment < ActiveRecord::Base
|
|||
end
|
||||
</ruby>
|
||||
|
||||
h3. Available callbacks
|
||||
h3. Available Callbacks
|
||||
|
||||
# TODO consider moving above the code examples and details, possibly combining with intro lifecycle stuff?
|
||||
|
||||
|
@ -825,7 +819,7 @@ h3. Halting Execution
|
|||
|
||||
As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the +before_create+, +before_save+, +before_update+ or +before_destroy+ callback methods returns a boolean +false+ (not +nil+) value or raise and exception, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on. It's because the whole callback chain is wrapped in a transaction, so raising an exception or returning +false+ fires a database ROLLBACK.
|
||||
|
||||
h3. Callback classes
|
||||
h3. Callback Classes
|
||||
|
||||
Sometimes the callback methods that you'll write will be useful enough to be reused at other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.
|
||||
|
||||
|
@ -885,7 +879,7 @@ end
|
|||
|
||||
As with callback classes, the observer's methods receive the observed model as a parameter.
|
||||
|
||||
h4. Registering observers
|
||||
h4. Registering Observers
|
||||
|
||||
Observers should be placed inside of your *app/models* directory and registered in your application's *config/environment.rb* file. For example, the +UserObserver+ above would be saved as *app/models/user_observer.rb* and registered in *config/environment.rb*.
|
||||
|
||||
|
@ -896,7 +890,7 @@ config.active_record.observers = :user_observer
|
|||
|
||||
As usual, settings in *config/environments/* take precedence over those in *config/environment.rb*. So, if you prefer that an observer not run in all environments, you can simply register it in a specific environment instead.
|
||||
|
||||
h4. Sharing observers
|
||||
h4. Sharing Observers
|
||||
|
||||
By default, Rails will simply strip 'observer' from an observer's name to find the model it should observe. However, observers can also be used to add behaviour to more than one model, and so it's possible to manually specify the models that our observer should observe.
|
||||
|
||||
|
|
Loading…
Reference in a new issue