aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides/source/activerecord_validations_callbacks.textile
diff options
context:
space:
mode:
Diffstat (limited to 'railties/guides/source/activerecord_validations_callbacks.textile')
-rw-r--r--railties/guides/source/activerecord_validations_callbacks.textile258
1 files changed, 146 insertions, 112 deletions
diff --git a/railties/guides/source/activerecord_validations_callbacks.textile b/railties/guides/source/activerecord_validations_callbacks.textile
index 28948eca77..01e52bf01e 100644
--- a/railties/guides/source/activerecord_validations_callbacks.textile
+++ b/railties/guides/source/activerecord_validations_callbacks.textile
@@ -1,38 +1,39 @@
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:
+* Understand the lifecycle 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 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 that respond to lifecycle events outside of the original class
endprologue.
-# TODO consider starting with an overview of what validations and callbacks are, and the object lifecycle
-# http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
-# http://api.rubyonrails.org/classes/ActiveRecord/Base.html
+h3. The Object Lifecycle
+
+During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object lifecycle</em> so that you can control your application and its data.
-h3. Overview of ActiveRecord Validation
+Validations allow you to ensure that only valid data is stored in your database. Callbacks and observers allow you to trigger logic before or after an alteration of an object's state.
-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?
+h3. Validations Overview
-h4. Why Use ActiveRecord Validations?
+Before you dive into the detail of validations in Rails, you should understand a bit about how validations fit into the big picture.
-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.
+h4. Why Use Validations?
-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:
+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
-* 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.
+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.
-# 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?
@@ -46,8 +47,8 @@ end
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>
+>> p = Person.new(:name => "John Doe")
+=> #<Person id: nil, name: "John Doe", created_at: nil, :updated_at: nil>
>> p.new_record?
=> true
>> p.save
@@ -89,7 +90,7 @@ Note that +save+ also has the ability to skip validations (and callbacks!) if pa
h4. Object#valid? and Object#invalid?
-To verify whether or not an object is valid, you can use the +valid?+ method. This runs validations and returns true if no errors were added to 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 added to the object, and false otherwise.
<ruby>
class Person < ActiveRecord::Base
@@ -97,12 +98,12 @@ class Person < ActiveRecord::Base
end
Person.create(:name => "John Doe").valid? # => true
-Person.create.valid? # => false
+Person.create(:name => nil).valid? # => false
</ruby>
When Active Record is performing validations, any errors found are collected into an +errors+ instance variable and can be accessed through an +errors+ instance method. An object is considered invalid if it has errors, and calling +save+ or +save!+ will not save it to the database.
-However, 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
@@ -112,20 +113,25 @@ end
>> p = Person.new
=> #<Person id: nil, name: nil>
>> p.errors
-=> #<ActiveRecord::Errors:0x3b8b46c @base=#<Person id: nil, name: nil>, @errors={}>
+=> #<ActiveRecord::Errors..., @errors={}>
+
>> p.valid?
=> false
>> p.errors
-=> #<ActiveRecord::Errors:0x3b8b46c @base=#<Person id: nil, name: nil>, @errors={"name"=>["can't be blank"]}>
+=> #<ActiveRecord::Errors..., @errors={"name"=>["can't be blank"]}>
+
>> p = Person.create
=> #<Person id: nil, name: nil>
>> p.errors
-=> #<ActiveRecord::Errors:0x3b8b46c @base=#<Person id: nil, name: nil>, @errors={"name"=>["can't be blank"]}>
+=> #<ActiveRecord::Errors..., @errors={"name"=>["can't be blank"]}>
+
>> p.save
=> false
+
>> p.save!
=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
->> p = Person.create!
+
+>> Person.create!
=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
</ruby>
@@ -140,7 +146,9 @@ end
>> Person.create.errors.invalid?(:name) # => true
</ruby>
-h3. Declarative Validation Helpers
+We'll cover validation errors in greater depth in the *Working with Validation Errors* section. For now, let's turn to the built-in validation helpers that Rails provides by default.
+
+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 +317,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
@@ -322,7 +329,7 @@ class Person < ActiveRecord::Base
end
</ruby>
-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.
+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
@@ -331,7 +338,7 @@ class LineItem < ActiveRecord::Base
end
</ruby>
-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
+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 that +Object#blank?+ handles boolean values (+false.blank? # => true+).
The default error message for +validates_presence_of+ is "_can't be empty_".
@@ -429,11 +436,11 @@ 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.
-h4. Using a symbol with :if and :unless
+h4. 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.
@@ -447,7 +454,7 @@ class Order < ActiveRecord::Base
end
</ruby>
-h4. Using a string with the :if and :unless
+h4. 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.
@@ -457,7 +464,7 @@ class Person < ActiveRecord::Base
end
</ruby>
-h4. Using a Proc object with :if and :unless
+h4. Using a Proc with :if and :unless
Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object which will be called. Using a Proc object can give you the ability to write a condition that will be executed only when the validation happens and not when your code is loaded by the Ruby interpreter. This option is best suited when writing short validation methods, usually one-liners.
@@ -468,9 +475,13 @@ class Account < ActiveRecord::Base
end
</ruby>
-h3. Writing your own validation methods
+h3. Creating 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.
+When the built-in validation helpers are not enough for your needs, you can write your own validation methods.
+
+Simply 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 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.
<ruby>
class Invoice < ActiveRecord::Base
@@ -506,7 +517,7 @@ module ActiveRecord
end
</ruby>
-The recipe is simple: just create a new validation method inside the +ActiveRecord::Validations::ClassMethods+ module. You can put this code in a file inside your application's *lib* folder, and then requiring it from your *environment.rb* or any other file inside *config/initializers*. You can use this helper like this:
+Simply create a new validation method inside the +ActiveRecord::Validations::ClassMethods+ module. You can put this code in a file inside your application's *lib* folder, and then requiring it from your *environment.rb* or any other file inside *config/initializers*. You can use this helper like this:
<ruby>
class Person < ActiveRecord::Base
@@ -514,15 +525,15 @@ class Person < ActiveRecord::Base
end
</ruby>
-h3. Manipulating the errors collection
+h3. Working with 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?)
+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.
-You can do more than just call +valid?+ upon your objects based on the existence of the +errors+ collection. Here is a list of the other available methods that you can use to manipulate errors or ask for an object's state.
+The following is a list of the most commonly used methods. Please refer to the ActiveRecord::Errors documentation for an exhaustive list that covers all of the available methods.
-* +add_to_base+ lets you add errors 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 it's attributes. +add_to_base+ receives a string with the message.
+h4. errors.add_to_base
+
++add_to_base+ lets you add errors 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 it's attributes. +add_to_base+ simply receives a string and uses this as the error message.
<ruby>
class Person < ActiveRecord::Base
@@ -532,28 +543,29 @@ class Person < ActiveRecord::Base
end
</ruby>
-* +add+ lets you manually add messages that are related to particular attributes. When writing those messages, keep in mind that Rails will prepend them with the name of the attribute that holds the error, so write it in a way that makes sense. +add+ receives a symbol with the name of the attribute that you want to add the message to and the message itself.
+h4. errors.add
+
++add+ lets you manually add messages that are related to particular attributes. Note that Rails will prepend the name of the attribute to the error message you pass it. You can use the +full_messages+ method to view the messages in the form they might be displayed to a user. +add+ receives a symbol with the name of the attribute that 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, "can't have the characters !@#$%*()_-+=")
+ errors.add(:name, "cannot contain the characters !@#$%*()_-+=")
end
end
-</ruby>
-* +invalid?+ is used when you want to check if a particular attribute is invalid. It receives a symbol with the name of the attribute that you want to check.
+person = Person.create(:name => "!@#$")
-<ruby>
-class Person < ActiveRecord::Base
- validates_presence_of :name, :email
-end
+person.errors.on(:name)
+# => "is too short (minimum is 3 characters)"
-person = Person.new(:name => "John Doe")
-person.errors.invalid?(:email) # => true
+person.errors.full_messages
+# => ["Name is too short (minimum is 3 characters)"]
</ruby>
-* +on+ is used when you want to check the error messages for a specific attribute. It will return different kinds of objects depending on the state of the +errors+ collection for the given attribute. If there are no errors related to the attribute, +on+ will return +nil+. If there is just one errors message for this attribute, +on+ will return a string with the message. When +errors+ holds two or more error messages for the attribute, +on+ will return an array of strings, each one with one error message.
+h4. errors.on
+
++on+ is used when you want to check the error messages for a specific attribute. It will return different kinds of objects depending on the state of the +errors+ collection for the given attribute. If there are no errors related to the attribute, +on+ will return +nil+. If there is just one errors message for this attribute, +on+ will return a string with the message. When +errors+ holds two or more error messages for the attribute, +on+ will return an array of strings, each one with one error message.
<ruby>
class Person < ActiveRecord::Base
@@ -576,7 +588,9 @@ person.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
</ruby>
-* +clear+ is used when you intentionally want to clear all the messages in the +errors+ collection. However, calling +errors.clear+ upon an invalid object won't 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. If any of them fails, the +errors+ collection will get filled again.
+h4. errors.clear
+
++clear+ 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
@@ -591,17 +605,35 @@ person.errors.on(:name)
person.errors.clear
person.errors.empty? # => true
+
p.save # => false
+
p.errors.on(:name)
# => ["can't be blank", "is too short (minimum is 3 characters)"]
</ruby>
-# TODO consider discussing other methods (e.g. errors.size)
-# http://api.rubyonrails.org/classes/ActiveRecord/Errors.html
+h4. errors.size
+
++size+ returns the total number of errors added. Two errors added to the same object will be counted as such.
+
+<ruby>
+class Person < ActiveRecord::Base
+ validates_presence_of :name
+ validates_length_of :name, :minimum => 3
+end
+
+person = Person.new
+person.valid? # => false
+person.errors.size # => 2
+</ruby>
+
+h3. Displaying Validation Errors in the View
+
+Rails provides built-in helpers to display the error messages of your models in your view templates.
-h3. Using error collection in views
+h4. error_messages and error_messages_for
-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.
+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
@@ -651,6 +683,8 @@ Which results in the following content
If you pass +nil+ to any of these options, it will get rid of the respective section of the +div+.
+h4. Customizing the Error Messages CSS
+
It's also possible to change the CSS classes used by the +error_messages+ helper. These classes are automatically defined at the *scaffold.css* file, generated by the scaffold script. If you're not using scaffolding, you can still define those CSS classes at your CSS files. Here is a list of the default CSS classes.
* +.fieldWithErrors+ - Style for the form fields with errors.
@@ -659,9 +693,11 @@ 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. Customizing the Error Messages HTML
+
+By default, form fields with errors are displayed enclosed by a +div+ element with the +fieldWithErrors+ CSS class. However, it's possible to override the way Rails treats those fields by default.
-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.
+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.
<ruby>
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
@@ -684,7 +720,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 +729,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 +748,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 +758,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 +774,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 +784,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,48 +806,43 @@ class Comment < ActiveRecord::Base
end
</ruby>
-h3. Available callbacks
-
-# TODO consider moving above the code examples and details, possibly combining with intro lifecycle stuff?
+h3. Available Callbacks
Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations.
-h4. Callbacks called both when creating or updating a record.
-
-# TODO consider just listing these in the possible lifecycle of an object, roughly as they do here:
-# http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
+h4. Creating and/or Updating an Object
* +before_validation+
* +after_validation+
* +before_save+
-* *INSERT OR UPDATE OPERATION*
+* INSERT OR UPDATE OPERATION
* +after_save+
-h4. Callbacks called only when creating a new record.
+h4. Creating an Object
* +before_validation_on_create+
* +after_validation_on_create+
* +before_create+
-* *INSERT OPERATION*
+* INSERT OPERATION
* +after_create+
-h4. Callbacks called only when updating an existing record.
+h4. Updating an Object
* +before_validation_on_update+
* +after_validation_on_update+
* +before_update+
-* *UPDATE OPERATION*
+* UPDATE OPERATION
* +after_update+
-h4. Callbacks called when removing a record from the database.
+h4. Destroying an Object
* +before_destroy+
-* *DELETE OPERATION*
+* DELETE OPERATION
* +after_destroy+
-The +before_destroy+ and +after_destroy+ callbacks will only be called if you delete the model using either the +destroy+ instance method or one of the +destroy+ or +destroy_all+ class methods of your Active Record class. If you use +delete+ or +delete_all+ no callback operations will run, since Active Record will not instantiate any objects, accessing the records to be deleted directly in the database.
+CAUTION: The +before_destroy+ and +after_destroy+ callbacks will only be called if you delete the model using either the +destroy+ instance method or one of the +destroy+ or +destroy_all+ class methods of your Active Record class. If you use +delete+ or +delete_all+ no callback operations will run, since Active Record will not instantiate any objects, accessing the records to be deleted directly in the database.
-h4. after_initialize and after_find callbacks
+h4. after_initialize and after_find
The +after_initialize+ callback will be called whenever an Active Record object is instantiated, either by directly using +new+ or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record +initialize+ method.
@@ -825,7 +854,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.
@@ -869,53 +898,58 @@ You can declare as many callbacks as you want inside your callback classes.
h3. Observers
-Active Record callbacks are a powerful feature, but they can pollute your model implementation with code that's not directly related to the model's purpose. In object-oriented software, it's always a good idea to design your classes with a single responsibility in the whole system. For example, it wouldn't make much sense to have a +User+ model with a method that writes data about a login attempt to a log file. Whenever you're using callbacks to write code that's not directly related to your model class purposes, it may be a good moment to create an Observer.
-
-An Active Record Observer is an object that links itself to a model and registers its methods for callbacks. Your model's implementation remains clean, while you can reuse the code in the Observer to add behaviour to more than one model class. OK, you may say that we can also do that using callback classes, but it would still force us to add code to our model's implementation.
+Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn't directly related to its purpose, observers allow you to add functionality outside of a model. For example, it could be argued that a +User+ model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn't directly related to your model, you may want to consider creating an observer instead.
-Observer classes are subclasses of the ActiveRecord::Observer class. When this class is subclassed, Active Record will look at the name of the new class and then strip the 'Observer' part to find the name of the Active Record class to observe.
+h4. Creating observers
-Consider a Registration model, where we want to send an email every time a new registration is created. Since sending emails is not directly related to our model's purpose, we could create an Observer to do just that:
+For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we could create an observer to contain this functionality.
<ruby>
-class RegistrationObserver < ActiveRecord::Observer
+class UserObserver < ActiveRecord::Observer
def after_create(model)
- # code to send registration confirmation emails...
+ # code to send confirmation email...
end
end
</ruby>
-Like in callback classes, the observer's methods receive the observed model as a parameter.
+As with callback classes, the observer's methods receive the observed model as a parameter.
-Sometimes using the ModelName + Observer naming convention won't be the best choice, mainly when you want to use the same observer for more than one model class. It's possible to explicity specify the models that our observer should observe.
+h4. Registering Observers
-<ruby>
-class Auditor < ActiveRecord::Observer
- observe User, Registration, Invoice
-end
-</ruby>
-
-h4. Registering observers
-
-If you paid attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiated and begin to interact with our models. For observers to work we need to register them somewhere. The usual place to do that is in our application's *config/environment.rb* file. In this file there is a commented-out line where we can define the observers that our application should load at start-up.
+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*.
<ruby>
# Activate observers that should always be running
-config.active_record.observers = :registration_observer, :auditor
+config.active_record.observers = :user_observer
</ruby>
-You can uncomment the line with +config.active_record.observers+ and change the symbols for the name of the observers that should be registered.
+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
-It's also possible to register callbacks in any of the files living at *config/environments/*, if you want an observer to work only in a specific environment. There is not a +config.active_record.observers+ line at any of those files, but you can simply add it.
+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.
-h4. Where to put the observers' source files
+<ruby>
+class MailerObserver < ActiveRecord::Observer
+ observe :registration, :user
+
+ def after_create(model)
+ # code to send confirmation email...
+ end
+end
+</ruby>
-By convention, you should always save your observers' source files inside *app/models*.
+In this example, the +after_create+ method would be called whenever a +Registration+ or +User+ was created. Note that this new +MailerObserver+ would also need to be registered in *config/environment.rb* in order to take effect.
-# TODO this probably doesn't need it's own section and entry in the table of contents.
+<ruby>
+# Activate observers that should always be running
+config.active_record.observers = :mailer_observer
+</ruby>
h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks
-January 9, 2009: Initial version by "Cássio Marques":credits.html#cmarques
+* February 10, 2009: Observers revision by Trevor Turk
+* February 5, 2009: Initial revision by Trevor Turk
+* January 9, 2009: Initial version by "Cássio Marques":credits.html#cmarques