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.textile234
1 files changed, 123 insertions, 111 deletions
diff --git a/railties/guides/source/activerecord_validations_callbacks.textile b/railties/guides/source/activerecord_validations_callbacks.textile
index b0e52e8be1..5ae4884297 100644
--- a/railties/guides/source/activerecord_validations_callbacks.textile
+++ b/railties/guides/source/activerecord_validations_callbacks.textile
@@ -57,7 +57,7 @@ We can see how it works by looking at some script/console output:
=> false
</shell>
-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 trigger the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an object in the database that's invalid. 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.
@@ -141,7 +141,7 @@ end
h4. +errors.invalid?+
-To verify whether or not a particular attribute of an object is valid, you can use the +errors.invalid?+ method. 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, but only if there are errors found on an individual attribute of the object.
+To verify whether or not a particular attribute of an object is valid, you can use the +errors.invalid?+ method. 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
@@ -152,7 +152,7 @@ end
>> Person.create.errors.invalid?(:name) # => true
</ruby>
-We'll cover validation errors in greater depth in the "Working with Validation Errors":#workingwith-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.
h3. Validation Helpers
@@ -164,7 +164,7 @@ All of them accept the +:on+ and +:message+ options, which define when the valid
h4. +validates_acceptance_of+
-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 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 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
@@ -193,7 +193,7 @@ class Library < ActiveRecord::Base
end
</ruby>
-This validation will work with all the association types.
+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.
@@ -316,9 +316,9 @@ The +validates_size_of+ helper is an alias for +validates_length_of+.
h4. +validates_numericality_of+
-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 +:integer_only+ 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 +:integer_only+ to +true+, then it will use the
+If you set +:only_integer+ to +true+, then it will use the
<ruby>
/\A[+-]?\d+\Z/
@@ -419,11 +419,11 @@ The block receives the model, the attribute's name and the attribute's value. Yo
h3. 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 are discussed later in the conditional validation 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 "Conditional Validation":#conditional-validation.
-h4. :allow_nil
+h4. +:allow_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+.
+The +:allow_nil+ option skips the validation when the value being validated is +nil+. Using +:allow_nil+ with +validates_presence_of+ allows for +nil+, but any other +blank?+ value will still be rejected.
<ruby>
class Coffee < ActiveRecord::Base
@@ -432,9 +432,9 @@ class Coffee < ActiveRecord::Base
end
</ruby>
-h4. :allow_blank
+h4. +: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 +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 +blank?+, like +nil+ or an empty string for example.
<ruby>
class Topic < ActiveRecord::Base
@@ -445,32 +445,32 @@ Topic.create("title" => "").valid? # => true
Topic.create("title" => nil).valid? # => true
</ruby>
-h4. :message
+h4. +: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, together with the attribute name.
+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.
-h4. :on
+h4. +: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 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.
<ruby>
class Person < ActiveRecord::Base
- # => it will be possible to update email with a duplicated value
+ # it will be possible to update email with a duplicated value
validates_uniqueness_of :email, :on => :create
- # => it will be possible to create the record with a 'non-numerical age'
+ # it will be possible to create the record with a non-numerical age
validates_numericality_of :age, :on => :update
- # => the default (validates on both create and update)
+ # the default (validates on both create and update)
validates_presence_of :name, :on => :save
end
</ruby>
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.
+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 +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.
@@ -484,9 +484,9 @@ class Order < ActiveRecord::Base
end
</ruby>
-h4. Using a String with :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.
+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
@@ -494,9 +494,9 @@ class Person < ActiveRecord::Base
end
</ruby>
-h4. Using a Proc 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.
+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
@@ -511,12 +511,12 @@ When the built-in validation helpers are not enough for your needs, you can writ
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.
+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
validate :expiration_date_cannot_be_in_the_past,
- :discount_cannot_be_more_than_total_value
+ :discount_cannot_be_greater_than_total_value
def expiration_date_cannot_be_in_the_past
errors.add(:expiration_date, "can't be in the past") if
@@ -524,8 +524,8 @@ class Invoice < ActiveRecord::Base
end
def discount_cannot_be_greater_than_total_value
- errors.add(:discount, "can't be greater than total value") unless
- discount <= total_value
+ errors.add(:discount, "can't be greater than total value") if
+ discount > total_value
end
end
</ruby>
@@ -533,25 +533,18 @@ end
You can even create your own validation helpers and reuse them in several different models. Here is an example where we create a custom validation helper to validate the format of fields that represent email addresses:
<ruby>
-module ActiveRecord
- module Validations
- module ClassMethods
- def validates_email_format_of(value)
- validates_format_of value,
- :with => /\A[\w\._%-]+@[\w\.-]+\.[a-zA-Z]{2,4}\z/,
- :if => Proc.new { |u| !u.email.blank? },
- :message => "Invalid format for email address"
- end
- end
+ActiveRecord::Base.class_eval do
+ def self.validates_as_radio(attr_name, n, options={})
+ validates_inclusion_of attr_name, {:in => 1..n}.merge(options)
end
end
</ruby>
-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:
+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:
<ruby>
-class Person < ActiveRecord::Base
- validates_email_format_of :email_address
+class Movie < ActiveRecord::Base
+ validates_as_radio :rating, 5
end
</ruby>
@@ -559,11 +552,11 @@ h3. 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 ActiveRecord::Errors documentation for an exhaustive list that covers all of the available methods.
+The following is a list of the most commonly used methods. Please refer to the +ActiveRecord::Errors+ documentation for a list of all the available methods.
-h4. errors.add_to_base
+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.
+The +add_to_base+ method 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 its attributes. +add_to_base+ simply receives a string and uses this as the error message.
<ruby>
class Person < ActiveRecord::Base
@@ -573,29 +566,29 @@ class Person < ActiveRecord::Base
end
</ruby>
-h4. errors.add
+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.
+The +add+ method lets you manually add messages that are related to particular attributes. You can use the +full_messages+ method 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 !@#$%*()_-+=")
+ errors.add(:name, "cannot contain the characters !@#%*()_-+=")
end
end
-person = Person.create(:name => "!@#$")
+person = Person.create(:name => "!@#")
person.errors.on(:name)
-# => "is too short (minimum is 3 characters)"
+ # => "cannot contain the characters !@#%*()_-+="
person.errors.full_messages
-# => ["Name is too short (minimum is 3 characters)"]
+ # => ["Name cannot contain the characters !@#%*()_-+="]
</ruby>
-h4. errors.on
+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.
+The +on+ method is used when you want to check the error messages for a specific attribute. It returns 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+ returns +nil+. If there is just one error message for this attribute +on+ returns a string with the message. When +errors+ holds two or more error messages for the attribute, +on+ returns an array of strings, each one with one error message.
<ruby>
class Person < ActiveRecord::Base
@@ -610,17 +603,17 @@ person.errors.on(:name) # => nil
person = Person.new(:name => "JD")
person.valid? # => false
person.errors.on(:name)
-# => "is too short (minimum is 3 characters)"
+ # => "is too short (minimum is 3 characters)"
person = Person.new
person.valid? # => false
person.errors.on(:name)
-# => ["can't be blank", "is too short (minimum is 3 characters)"]
+ # => ["can't be blank", "is too short (minimum is 3 characters)"]
</ruby>
-h4. errors.clear
+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.
+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
@@ -631,7 +624,7 @@ end
person = Person.new
person.valid? # => false
person.errors.on(:name)
-# => ["can't be blank", "is too short (minimum is 3 characters)"]
+ # => ["can't be blank", "is too short (minimum is 3 characters)"]
person.errors.clear
person.errors.empty? # => true
@@ -639,31 +632,36 @@ person.errors.empty? # => true
p.save # => false
p.errors.on(:name)
-# => ["can't be blank", "is too short (minimum is 3 characters)"]
+ # => ["can't be blank", "is too short (minimum is 3 characters)"]
</ruby>
-h4. errors.size
+h4. +errors.size+
-+size+ returns the total number of errors added. Two errors added to the same object will be counted as such.
+The +size+ method returns the total number of error messages for the object.
<ruby>
class Person < ActiveRecord::Base
validates_presence_of :name
- validates_length_of :name, :minimum => 3
+ validates_length_of :name, :minimum => 3
+ validates_presence_of :email
end
person = Person.new
person.valid? # => false
-person.errors.size # => 2
+person.errors.size # => 3
+
+person = Person.new(:name => "Andrea", :email => "andrea@example.com")
+person.valid? # => true
+person.errors.size # => 0
</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.
-h4. error_messages and error_messages_for
+h4. +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.
+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
@@ -689,6 +687,8 @@ end
<% end %>
</erb>
+To get the idea, if you submit the form with empty fields you typically get this back, though styles are indeed missing by default:
+
!images/error_messages.png(Error messages)!
You can also use the +error_messages_for+ helper to display the error messages of a model assigned to a view template. It's very similar to the previous example and will achieve exactly the same result.
@@ -715,48 +715,52 @@ If you pass +nil+ to any of these options, it will get rid of the respective sec
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.
+The selectors to customize the style of error messages are:
-* +.fieldWithErrors+ - Style for the form fields with errors.
+* +.fieldWithErrors+ - Style for the form fields and labels with errors.
* +#errorExplanation+ - Style for the +div+ element with the error messages.
* +#errorExplanation h2+ - Style for the header of the +div+ element.
* +#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.
+* +#errorExplanation ul li+ - Style for the list items with individual error messages.
+
+Scaffolding for example generates +public/stylesheets/scaffold.css+, which defines the red-based style you saw above.
+
+The name of the class and the id can be changed with the +:class+ and +:id+ options, accepted by both helpers.
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, 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+.
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|
if instance.error_message.kind_of?(Array)
- %(#{html_tag}<span class='validation-error'>&nbsp;
+ %(#{html_tag}<span class="validation-error">&nbsp;
#{instance.error_message.join(',')}</span>)
else
- %(#{html_tag}<span class='validation-error'>&nbsp;
+ %(#{html_tag}<span class="validation-error">&nbsp;
#{instance.error_message}</span>)
end
end
</ruby>
-This will result in something like the following content:
+This will result in something like the following:
!images/validation_error_messages.png(Validation error messages)!
-The way form fields with errors are treated is defined by the +ActionView::Base.field_error_proc+ Ruby Proc. This Proc receives two parameters:
-
-* A string with the HTML tag
-* An object of the +ActionView::Helpers::InstanceTag+ class.
-
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, validated, or loaded from the database.
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.
+In order to use the available callbacks, you need to register them. You can do that by implementing them as ordinary methods, and then using a macro-style class method to register them as callbacks.
<ruby>
class User < ActiveRecord::Base
@@ -766,7 +770,7 @@ class User < ActiveRecord::Base
protected
def ensure_login_has_a_value
- if self.login.nil?
+ if login.nil?
self.login = email unless email.blank?
end
end
@@ -779,7 +783,8 @@ The macro-style class methods can also receive a block. Consider using this styl
class User < ActiveRecord::Base
validates_presence_of :login, :email
- before_create {|user| user.name = user.login.capitalize if user.name.blank?}
+ before_create {|user| user.name = user.login.capitalize
+ if user.name.blank?}
end
</ruby>
@@ -789,29 +794,29 @@ 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. Creating and/or Updating an Object
-
-* +before_validation+
-* +after_validation+
-* +before_save+
-* INSERT OR UPDATE OPERATION
-* +after_save+
-
h4. Creating an Object
+* +before_validation+
* +before_validation_on_create+
+* +after_validation+
* +after_validation_on_create+
+* +before_save+
* +before_create+
* INSERT OPERATION
* +after_create+
+* +after_save+
h4. Updating an Object
+* +before_validation+
* +before_validation_on_update+
+* +after_validation+
* +after_validation_on_update+
+* +before_save+
* +before_update+
* UPDATE OPERATION
* +after_update+
+* +after_save+
h4. Destroying an Object
@@ -819,13 +824,15 @@ h4. Destroying an Object
* DELETE OPERATION
* +after_destroy+
-h4. after_initialize and after_find
+WARNING. +after_save+ runs both on create and update, but always _after_ the more specific callbacks +after_create+ and +after_update+, no matter the order in which the macro calls were executed.
+
+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.
-The +after_find+ callback will be called whenever Active Record loads a record from the database. When used together with +after_initialize+ it will run first, since Active Record will first read the record from the database and them create the model object that will hold it.
+The +after_find+ callback will be called whenever Active Record loads a record from the database. +after_find+ is called before +after_initialize+ if both are defined.
-The +after_initialize+ and +after_find+ callbacks are a bit different from the others, since the only way to register those callbacks is by defining them as methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries.
+The +after_initialize+ and +after_find+ callbacks are a bit different from the others. They have no +before_*+ counterparts, and the only way to register them is by defining them as regular methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries.
<ruby>
class User < ActiveRecord::Base
@@ -873,6 +880,7 @@ Additionally, the +after_find+ callback is triggered by the following finder met
* +all+
* +first+
* +find+
+* +find_all_by_<em>attribute</em>+
* +find_by_<em>attribute</em>+
* +find_by_<em>attribute</em>!+
* +last+
@@ -898,11 +906,13 @@ 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.
-If any callback methods return +false+ or raise an exception, the execution chain will be halted and the desired operation will not complete. This is because the whole callback chain is wrapped in a transaction, and raising an exception or returning +false+ fires a database ROLLBACK.
+The whole callback chain is wrapped in a transaction. If any before callback method returns exactly +false+ or raises an exception the execution chain gets halted and a ROLLBACK is issued. After callbacks can only accomplish that by raising an exception.
+
+WARNING. Raising an arbitrary exception may break code that expects +save+ and friends not to fail like that. The +ActiveRecord::Rollback+ exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised.
h3. Relational Callbacks
-Callbacks work through model relationships, and can even be defined by them. Let's take an example where a User has_many Posts. In our example, a User's Posts should be destroyed if the User is destroyed. So, we'll add an after_destroy callback to the User model by way of its relationship to the Post model.
+Callbacks work through model relationships, and can even be defined by them. Let's take an example where a user has many posts. In our example, a user's posts should be destroyed if the user is destroyed. So, we'll add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model.
<ruby>
class User < ActiveRecord::Base
@@ -928,11 +938,11 @@ Post destroyed
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.
+Like in validations, we can also make our callbacks conditional, calling them 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 +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 :if and :unless with a Symbol
+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.
+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 if the callback should be executed.
<ruby>
class Order < ActiveRecord::Base
@@ -940,9 +950,9 @@ class Order < ActiveRecord::Base
end
</ruby>
-h4. Using :if and :unless with a String
+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.
+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 Order < ActiveRecord::Base
@@ -950,9 +960,9 @@ class Order < ActiveRecord::Base
end
</ruby>
-h4. Using :if and :unless with a Proc
+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.
+Finally, it's possible to associate +:if+ and +:unless+ with a +Proc+ object. This option is best suited when writing short validation methods, usually one-liners.
<ruby>
class Order < ActiveRecord::Base
@@ -974,14 +984,15 @@ end
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.
+Sometimes the callback methods that you'll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.
-Here's an example where we create a class with a after_destroy callback for a PictureFile model.
+Here's an example where we create a class with an +after_destroy+ callback for a +PictureFile+ model.
<ruby>
class PictureFileCallbacks
def after_destroy(picture_file)
- File.delete(picture_file.filepath) if File.exists?(picture_file.filepath)
+ File.delete(picture_file.filepath)
+ if File.exists?(picture_file.filepath)
end
end
</ruby>
@@ -994,17 +1005,18 @@ class PictureFile < ActiveRecord::Base
end
</ruby>
-Note that we needed to instantiate a new PictureFileCallbacks object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method.
+Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method.
<ruby>
class PictureFileCallbacks
def self.after_destroy(picture_file)
- File.delete(picture_file.filepath) if File.exists?(picture_file.filepath)
+ File.delete(picture_file.filepath)
+ if File.exists?(picture_file.filepath)
end
end
</ruby>
-If the callback method is declared this way, it won't be necessary to instantiate a PictureFileCallbacks object.
+If the callback method is declared this way, it won't be necessary to instantiate a +PictureFileCallbacks+ object.
<ruby>
class PictureFile < ActiveRecord::Base
@@ -1016,9 +1028,9 @@ You can declare as many callbacks as you want inside your callback classes.
h3. Observers
-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.
+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 the same 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.
-h4. Creating observers
+h4. Creating Observers
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.
@@ -1034,18 +1046,18 @@ As with callback classes, the observer's methods receive the observed model as a
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*.
+Observers are conventionally 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+ this way:
<ruby>
# Activate observers that should always be running
config.active_record.observers = :user_observer
</ruby>
-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.
+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
-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.
+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.
<ruby>
class MailerObserver < ActiveRecord::Observer
@@ -1057,7 +1069,7 @@ class MailerObserver < ActiveRecord::Observer
end
</ruby>
-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.
+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.
<ruby>
# Activate observers that should always be running