From e46c80765525817a89b784e6336a9f66250d53fc Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Tue, 13 Jan 2009 05:15:07 +0000 Subject: Regenerate html --- .../doc/guides/html/actioncontroller_basics.html | 8 +- .../html/activerecord_validations_callbacks.html | 206 ++++++++++----------- 2 files changed, 107 insertions(+), 107 deletions(-) (limited to 'railties/doc/guides') diff --git a/railties/doc/guides/html/actioncontroller_basics.html b/railties/doc/guides/html/actioncontroller_basics.html index 1c0cc0c040..c859a2893e 100644 --- a/railties/doc/guides/html/actioncontroller_basics.html +++ b/railties/doc/guides/html/actioncontroller_basics.html @@ -509,14 +509,14 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
# Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]
 config.action_controller.session_store = :active_record_store
-

4.1. Accessing the Session

+

4.1. Accessing the Session

In your controller you can access the session through the session instance method.

- +
Note Sessions are lazily loaded. If you don’t access sessions in your action’s code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.Sessions are lazily loaded. If you don’t access sessions in your action’s code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.

Session values are stored using key/value pairs like a hash:

@@ -572,7 +572,7 @@ http://www.gnu.org/software/src-highlite --> end

To reset the entire session, use reset_session.

-

4.2. The flash

+

4.2. The flash

The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let’s use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:

end end
-

4.2.1. flash.now

+

4.2.1. flash.now

By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create action fails to save a resource and you render the new template directly, that’s not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use flash.now in the same way you use the normal flash:

class Person < ActiveRecord::Base
 end
-

We can see how it works by looking at the following script/console output:

+

We can see how it works by looking at some script/console output:

>> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979"))
@@ -424,25 +422,25 @@ http://www.gnu.org/software/src-highlite -->
 >> p.new_record?
 => false
-

Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either save or update_attributes) will result in a SQL update operation. Active Record will use these facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you’re creating a new record or when you’re updating an existing one.

+

Saving new records means sending an SQL INSERT operation to the database, while saving existing records (by calling either save or update_attributes) will result in a SQL UPDATE operation. Active Record will use these facts to perform validations upon your objects, keeping them out of the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you’re creating a new record or when you’re updating an existing one.

- +
Caution There are four methods that when called will trigger validation: save, save!, update_attributes and update_attributes!. There is one method left, which is update_attribute. This method will update the value of an attribute without triggering any validation, so be careful when using update_attribute, since it can let you save your objects in an invalid state.There are four methods that when called will trigger validation: save, save!, update_attributes and update_attributes!. There is one update method for Active Record objects left, which is update_attribute. This method will update the value of an attribute without triggering any validation. Be careful when using update_attribute, because it can let you save your objects in an invalid state.
-

2.2. The meaning of valid

-

For verifying if an object is valid, Active Record uses the valid? method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the errors instance method. The proccess is really simple: If the errors method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the errors collection.

+

1.3. The Meaning of valid

+

To verify whether an object is valid, Active Record uses the valid? method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the errors instance method. The process is really simple: If the errors method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the errors collection.

-

3. The declarative validation helpers

+

2. The Declarative Validation Helpers

-

Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validations rules that are commonly used in most of the applications that you’ll write, so you don’t need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object’s errors collection, this message being associated with the field being validated.

-

Each helper accepts an arbitrary number of attributes, received as symbols, so with a single line of code you can add the same kind of validation to several attributes.

-

All these helpers accept the :on and :message options, which define when the validation should be applied and what message should be added to the errors collection when it fails, respectively. The :on option takes one of the values :save (it’s the default), :create or :update. There is a default error message for each one of the validation helpers. These messages are used when the :message option isn’t used. Let’s take a look at each one of the available helpers, listed in alphabetic order.

-

3.1. The validates_acceptance_of helper

-

Validates that a checkbox has been checked for agreement purposes. It’s normally used when the user needs to agree with your application’s terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually this acceptance does not need to be recorded anywhere in your database (if you don’t have a field for it, the helper will just create a virtual attribute).

+

Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validation rules that are commonly used. Every time a validation fails, an error message is added to the object’s errors collection, and this message is associated with the field being validated.

+

Each helper accepts an arbitrary number of attributes identified by symbols, so with a single line of code you can add the same kind of validation to several attributes.

+

All these helpers accept the :on and :message options, which define when the validation should be applied and what message should be added to the errors collection when it fails, respectively. The :on option takes one of the values :save (the default), :create or :update. There is a default error message for each one of the validation helpers. These messages are used when the :message option isn’t used. Let’s take a look at each one of the available helpers.

+

2.1. The validates_acceptance_of helper

+

Validates that a checkbox on the user interface was checked when a form was submitted. This is normally used when the user needs to agree to your application’s terms of service, confirm reading some text, or any similar concept. This validation is very specific to web applications and actually this acceptance does not need to be recorded anywhere in your database (if you don’t have a field for it, the helper will just create a virtual attribute).

validates_acceptance_of :terms_of_service end

The default error message for validates_acceptance_of is "must be accepted"

-

validates_acceptance_of can receive an :accept option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it.

+

validates_acceptance_of can receive an :accept option, which determines the value that will be considered acceptance. It defaults to "1", but you can change this.

class Person < ActiveRecord::Base
   validates_acceptance_of :terms_of_service, :accept => 'yes'
 end
-

3.2. The validates_associated helper

+

2.2. The validates_associated helper

You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, valid? will be called upon each one of the associated objects.

Caution -Pay attention not to use validates_associated on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack. +Don’t use validates_associated on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.
-

The default error message for validates_associated is "is invalid". Note that the errors for each failed validation in the associated objects will be set there and not in this model.

-

3.3. The validates_confirmation_of helper

-

You should use this helper when you have two text fields that should receive exactly the same content, like when you want to confirm an email address or password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with _confirmation appended.

+

The default error message for validates_associated is "is invalid". Note that each associated object will contain its own errors collection; errors do not bubble up to the calling model.

+

2.3. The validates_confirmation_of helper

+

You should use this helper when you have two text fields that should receive exactly the same content. For example, you may want to confirm an email address or a password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with _confirmation appended.

end

In your view template you could use something like

-
+
<%= text_field :person, :email %>
-<%= text_field :person, :email_confirmation %>
-
+<%= text_field :person, :email_confirmation %>
- +
@@ -516,7 +516,7 @@ http://www.gnu.org/software/src-highlite --> validates_presence_of :email_confirmation end

The default error message for validates_confirmation_of is "doesn’t match confirmation"

-

3.4. The validates_exclusion_of helper

+

2.4. The validates_exclusion_of helper

This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.

validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed" end
-

The validates_exclusion_of helper has an option :in that receives the set of values that will not be accepted for the validated attributes. The :in option has an alias called :within that you can use for the same purpose, if you’d like to. In the previous example we used the :message option to show how we can personalize it with the current attribute’s value, through the %s format mask.

+

The validates_exclusion_of helper has an option :in that receives the set of values that will not be accepted for the validated attributes. The :in option has an alias called :within that you can use for the same purpose, if you’d like to. This example uses the :message option to show how you can personalize it with the current attribute’s value, through the %s format mask.

The default error message for validates_exclusion_of is "is not included in the list".

-

3.5. The validates_format_of helper

-

This helper validates the attributes’s values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the :with option.

+

2.5. The validates_format_of helper

+

This helper validates the attributes' values by testing whether they match a given pattern. This pattern must be specified using a Ruby regular expression, which is specified using the :with option.

:message => "Only letters allowed" end

The default error message for validates_format_of is "is invalid".

-

3.6. The validates_inclusion_of helper

+

2.6. The validates_inclusion_of helper

This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.

validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size" end
-

The validates_inclusion_of helper has an option :in that receives the set of values that will be accepted. The :in option has an alias called :within that you can use for the same purpose, if you’d like to. In the previous example we used the :message option to show how we can personalize it with the current attribute’s value, through the %s format mask.

+

The validates_inclusion_of helper has an option :in that receives the set of values that will be accepted. The :in option has an alias called :within that you can use for the same purpose, if you’d like to. The previous example uses the :message option to show how you can personalize it with the current attribute’s value, through the %s format mask.

The default error message for validates_inclusion_of is "is not included in the list".

-

3.7. The validates_length_of helper

-

This helper validates the length of your attribute’s value. It can receive a variety of different options, so you can specify length contraints in different ways.

+

2.7. The validates_length_of helper

+

This helper validates the length of your attribute’s value. It includes a variety of different options, so you can specify length constraints in different ways:

-

The default error messages depend on the type of length validation being performed. You can personalize these messages, using the :wrong_length, :too_long and :too_short options and the %d format mask as a placeholder for the number corresponding to the length contraint being used. You can still use the :message option to specify an error message.

+

The default error messages depend on the type of length validation being performed. You can personalize these messages, using the :wrong_length, :too_long and :too_short options and the %d format mask as a placeholder for the number corresponding to the length constraint being used. You can still use the :message option to specify an error message.

class Person < ActiveRecord::Base
   validates_length_of :bio, :too_long => "you're writing too much. %d characters is the maximum allowed."
 end
-

This helper has an alias called validates_size_of, it’s the same helper with a different name. You can use it if you’d like to.

-

3.8. The validates_numericality_of helper

+

The validates_size_of helper is an alias for validates_length_of.

+

2.8. The validates_numericality_of helper

This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the :integer_only option set to true, you can specify that only integral numbers are allowed.

-

If you use :integer_only set to true, then it will use the /\A[+\-]?\d+\Z/+ regular expression to validate the attribute’s value. Otherwise, it will try to convert the value using +Kernel.Float.

+

If you set :integer_only to true, then it will use the /\A[+\-]?\d+\Z/+ regular expression to validate the attribute’s value. Otherwise, it will try to convert the value to a number using +Kernel.Float.

validates_numericality_of :games_played, :integer_only => true end

The default error message for validates_numericality_of is "is not a number".

-

3.9. The validates_presence_of helper

-

This helper validates that the attributes are not empty. It uses the blank? method to check if the value is either nil or an empty string (if the string has only spaces, it will still be considered empty).

+

2.9. The validates_presence_of helper

+

This helper validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or an empty string (if the string has only spaces, it will still be considered empty).

Note If you want to be sure that an association is present, you’ll need to test if the foreign key used to map the association is present, and not the associated object itself.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.
@@ -645,12 +645,12 @@ http://www.gnu.org/software/src-highlite --> Note -If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true +If you want to validate the presence of a boolean field (where the real values are true and false), you should use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true

The default error message for validates_presence_of is "can’t be empty".

-

3.10. The validates_uniqueness_of helper

-

This helper validates that the attribute’s value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an unique index in your database.

+

2.10. The validates_uniqueness_of helper

+

This helper validates that the attribute’s value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create an unique index in your database.

validates_uniqueness_of :email end

The validation happens by performing a SQL query into the model’s table, searching for a record where the attribute that must be validated is equal to the value in the object being validated.

-

There is a :scope option that you can use to specify other attributes that must be used to define uniqueness:

+

There is a :scope option that you can use to specify other attributes that are used to limit the uniqueness check:

validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year" end
-

There is also a :case_sensitive option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.

+

There is also a :case_sensitive option that you can use to define whether the uniqueness constraint will be case sensitive or not. This option defaults to true.

validates_uniqueness_of :name, :case_sensitive => false end

The default error message for validates_uniqueness_of is "has already been taken".

-

3.11. The validates_each helper

+

2.11. The validates_each helper

This helper validates attributes against a block. It doesn’t have a predefined validation function. You should create one using a block, and every attribute passed to validates_each will be tested against it. In the following example, we don’t want names and surnames to begin with lower case.

model.errors.add(attr, 'Must start with upper case') if value =~ /^[a-z]/ end end
-

The block receives the model, the attribute’s name and the attribute’s value. If your validation fails, you can add an error message to the model, therefore making it invalid.

+

The block receives the model, the attribute’s name and the attribute’s value. You can do anything you like to check for valid data within the block. If your validation fails, you can add an error message to the model, therefore making it invalid.

-

4. Common validation options

+

3. Common Validation Options

-

There are some common options that all the validation helpers can use. Here they are, except for the :if and :unless options, which we’ll cover right at the next topic.

-

4.1. The :allow_nil option

-

You may use the :allow_nil option everytime you want to trigger a validation only if the value being validated is not nil. You may be asking yourself if it makes any sense to use :allow_nil and validates_presence_of together. Well, it does. Remember, validation will be skipped only for nil attributes, but empty strings are not considered nil.

+

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.

+

3.1. The :allow_nil option

+

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.

validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size", :allow_nil => true end
-

4.2. The :allow_blank option

-

In compliment to :allow_nil we have :allow_blank. This option will let validation pass if the attribute’s value is nil or an empty string, i.e., any value that returns true for blank?.

+

3.2. The :allow_blank option

+

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?.

Topic.create("title" => "").valid? # => true Topic.create("title" => nil).valid? # => true
-

4.3. The :message option

-

As stated before, the :message option lets you specify the message that will be added to the errors collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.

-

4.4. The :on option

-

As stated before, the :on option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran on save (both when you’re creating a new record and when you’re updating it). If you want to change it, you can use :on => :create to run the validation only when a new record is created or :on => :update to run the validation only when a record is updated.

+

3.3. The :message option

+

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.

+

3.4. The :on option

+

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.

# => it will be possible to create the record with a 'non-numerical age' validates_numericality_of :age, :on => :update - # => the default + # => the default (validates on both create and update) validates_presence_of :name, :on => :save end
-

5. Conditional validation

+

4. 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.

-

5.1. Using a symbol with the :if and :unless options

+

4.1. Using a symbol with the :if and :unless options

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.

payment_type == "card" end end
-

5.2. Using a string with the :if and :unless options

+

4.2. Using a string with the :if and :unless options

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.

class Person < ActiveRecord::Base
   validates_presence_of :surname, :if => "name.nil?"
 end
-

5.3. Using a Proc object with the :if and :unless options

+

4.3. Using a Proc object with the :if and :unless options

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 hability 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.

:unless => Proc.new { |a| a.password.blank? } end
-

6. Writing your own validation methods

+

5. Writing your own 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.

@@ -830,7 +830,7 @@ http://www.gnu.org/software/src-highlite --> validates_email_format_of :email_address end
-

7. Manipulating the errors collection

+

6. Manipulating the errors collection

You can do more than just call valid? upon your objects based on the existance 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.

    @@ -943,7 +943,7 @@ p.save .errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
-

8. Using the errors collection in your view templates

+

7. Using the errors collection in your view templates

Rails provides built-in helpers to display the error messages of your models in your view templates. It may be useful to display those messages when you’re trying to create or edit a record and validation fails. If you’re using the form_for helper to create a form, you can use it to call the error_messages method, which creates a div element containing all the error messages for the model associated with the form. Here is a simple example, using a Product model and the view template generated with the scaffold script.

@@ -1025,7 +1025,7 @@ http://www.gnu.org/software/src-highlite -->

-

8.1. Changing the way form fields with errors are displayed

+

7.1. 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.

-

10. Conditional callbacks

+

9. 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.

-

10.1. Using a symbol with the :if and :unless options

+

9.1. Using a symbol with the :if and :unless options

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.

class Order < ActiveRecord::Base
   before_save :normalize_card_number, :if => :paid_with_card?
 end
-

10.2. Using a string with the :if and :unless options

+

9.2. Using a string with the :if and :unless options

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.

class Order < ActiveRecord::Base
   before_save :normalize_card_number, :if => "paid_with_card?"
 end
-

10.3. Using a Proc object with the :if and :unless options

+

9.3. Using a Proc object with the :if and :unless options

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.

before_save :normalize_card_number, :if => Proc.new { |order| order.paid_with_card? } end
-

10.4. Multiple Conditions for Callbacks

+

9.4. Multiple Conditions for Callbacks

When writing conditional callbacks, it’s possible to mix both :if and :unless in the same callback declaration.

:unless => Proc.new { |comment| comment.post.ignore_comments? } end
-

11. Available callbacks

+

10. 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.

-

11.1. Callbacks called both when creating or updating a record.

+

10.1. Callbacks called both when creating or updating a record.

  • @@ -1180,7 +1180,7 @@ http://www.gnu.org/software/src-highlite -->

-

11.2. Callbacks called only when creating a new record.

+

10.2. Callbacks called only when creating a new record.

  • @@ -1208,7 +1208,7 @@ http://www.gnu.org/software/src-highlite -->

-

11.3. Callbacks called only when updating an existing record.

+

10.3. Callbacks called only when updating an existing record.

  • @@ -1236,7 +1236,7 @@ http://www.gnu.org/software/src-highlite -->

-

11.4. Callbacks called when removing a record from the database.

+

10.4. Callbacks called when removing a record from the database.

  • @@ -1255,16 +1255,16 @@ http://www.gnu.org/software/src-highlite -->

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.

-

11.5. The after_initialize and after_find callbacks

+

10.5. The after_initialize and after_find callbacks

The after_initialize callback will be called whenever an Active Record object is instantiated, either by direcly 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_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.

-

12. Halting Execution

+

11. 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.

-

13. Callback classes

+

12. 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.

Here’s an example where we create a class with a after_destroy callback for a PictureFile model.

@@ -1309,7 +1309,7 @@ http://www.gnu.org/software/src-highlite --> end

You can declare as many callbacks as you want inside your callback classes.

-

14. Observers

+

13. 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.

@@ -1335,7 +1335,7 @@ http://www.gnu.org/software/src-highlite -->
class Auditor < ActiveRecord::Observer
   observe User, Registration, Invoice
 end
-

14.1. Registering observers

+

13.1. 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.

config.active_record.observers = :registration_observer, :auditor

You can uncomment the line with config.active_record.observers and change the symbols for the name of the observers that should be registered.

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.

-

14.2. Where to put the observers' source files

+

13.2. Where to put the observers' source files

By convention, you should always save your observers' source files inside app/models.

-

15. Changelog

+

14. Changelog

-- cgit v1.2.3