active_record_validations_callbacks.textile 48.1 KB
Newer Older
1 2
h2. Active Record Validations and Callbacks

3
This guide teaches you how to hook into the life cycle 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 life cycle.
4 5 6

After reading this guide and trying out the presented concepts, we hope that you'll be able to:

7
* Understand the life cycle of Active Record objects
8 9 10
* Use the built-in Active Record validation helpers
* Create your own custom validation methods
* Work with the error messages generated by the validation process
11
* Create callback methods that respond to events in the object life cycle
12
* Create special classes that encapsulate common behavior for your callbacks
13
* Create Observers that respond to life cycle events outside of the original class
14 15 16

endprologue.

17
h3. The Object Life Cycle
P
Pratik Naik 已提交
18

19
During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object life cycle</em> so that you can control your application and its data.
20

P
Pratik Naik 已提交
21
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.
22

P
Pratik Naik 已提交
23
h3. Validations Overview
24

P
Pratik Naik 已提交
25
Before you dive into the detail of validations in Rails, you should understand a bit about how validations fit into the big picture.
26

P
Pratik Naik 已提交
27
h4. Why Use Validations?
28

P
Pratik Naik 已提交
29
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.
30

P
Pratik Naik 已提交
31
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.
32

P
Pratik Naik 已提交
33
* 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.
P
Pratik Naik 已提交
34
* 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.
P
Pratik Naik 已提交
35
* 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.
36
* 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.
37 38 39

h4. When Does Validation Happen?

P
Pratik Naik 已提交
40
There are two kinds of Active Record objects: those that correspond to a row inside your database and those that do not. When you create a fresh object, for example using the +new+ method, that object does not belong to the database yet. Once you call +save+ upon that object it will be saved into the appropriate database table. Active Record uses the +new_record?+ instance method to determine whether an object is already in the database or not. Consider the following simple Active Record class:
41 42 43 44 45 46

<ruby>
class Person < ActiveRecord::Base
end
</ruby>

47
We can see how it works by looking at some +rails console+ output:
48 49

<shell>
P
Pratik Naik 已提交
50 51
>> p = Person.new(:name => "John Doe")
=> #<Person id: nil, name: "John Doe", created_at: nil, :updated_at: nil>
52 53 54 55 56 57 58 59
>> p.new_record?
=> true
>> p.save
=> true
>> p.new_record?
=> false
</shell>

60
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.
61 62 63

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.

P
Pratik Naik 已提交
64
The following methods trigger validations, and will save the object to the database only if the object is valid:
65 66 67 68 69 70 71 72 73

* +create+
* +create!+
* +save+
* +save!+
* +update+
* +update_attributes+
* +update_attributes!+

74
The bang versions (e.g. +save!+) raise an exception if the record is invalid. The non-bang versions don't: +save+ and +update_attributes+ return +false+, +create+ and +update+ just return the objects.
P
Pratik Naik 已提交
75

76 77 78 79 80 81 82 83 84 85 86 87 88
h4. Skipping Validations

The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution.

* +decrement!+
* +decrement_counter+
* +increment!+
* +increment_counter+
* +toggle!+
* +update_all+
* +update_attribute+
* +update_counters+

89
Note that +save+ also has the ability to skip validations if passed +:validate => false+ as argument. This technique should be used with caution.
90

91
* +save(:validate => false)+
92

P
Pratik Naik 已提交
93
h4. +valid?+ and +invalid?+
94

P
Pratik Naik 已提交
95
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.
96 97 98

<ruby>
class Person < ActiveRecord::Base
99
  validates :name, :presence => true
100 101 102
end

Person.create(:name => "John Doe").valid? # => true
P
Pratik Naik 已提交
103
Person.create(:name => nil).valid? # => false
104 105
</ruby>

P
Pratik Naik 已提交
106
When Active Record is performing validations, any errors found can be accessed through the +errors+ instance method. By definition an object is valid if this collection is empty after running validations.
107

P
Pratik Naik 已提交
108
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+.
109 110 111

<ruby>
class Person < ActiveRecord::Base
112
  validates :name, :presence => true
113 114 115 116 117
end

>> p = Person.new
=> #<Person id: nil, name: nil>
>> p.errors
118
=> {}
119

120 121 122
>> p.valid?
=> false
>> p.errors
123
=> {:name=>["can't be blank"]}
P
Pratik Naik 已提交
124

125 126 127
>> p = Person.create
=> #<Person id: nil, name: nil>
>> p.errors
128
=> {:name=>["can't be blank"]}
129

130 131
>> p.save
=> false
P
Pratik Naik 已提交
132

133 134
>> p.save!
=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
P
Pratik Naik 已提交
135 136

>> Person.create!
137 138 139
=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
</ruby>

P
Pratik Naik 已提交
140 141
+invalid?+ is simply the inverse of +valid?+. +invalid?+ triggers your validations and returns true if any errors were added to the object, and false otherwise.

142
h4(#validations_overview-errors). +errors[]+
P
Pratik Naik 已提交
143

X
Xavier Noria 已提交
144
To verify whether or not a particular attribute of an object is valid, you can use +errors[:attribute]+. It returns an array of all the errors for +:attribute+. If there are no errors on the specified attribute, an empty array is returned.
145 146

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.
147 148 149

<ruby>
class Person < ActiveRecord::Base
150
  validates :name, :presence => true
151 152
end

153 154
>> Person.new.errors[:name].any? # => false
>> Person.create.errors[:name].any? # => true
155 156
</ruby>

P
Pratik Naik 已提交
157
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.
P
Pratik Naik 已提交
158 159

h3. Validation Helpers
160

P
Pratik Naik 已提交
161
Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. 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.
162

P
Pratik Naik 已提交
163
Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes.
164

P
Pratik Naik 已提交
165
All of them accept the +:on+ and +:message+ options, which define when the validation should be run and what message should be added to the +errors+ collection if 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 specified. Let's take a look at each one of the available helpers.
166

P
Pratik Naik 已提交
167
h4. +validates_acceptance_of+
168

P
Pratik Naik 已提交
169
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).
170 171 172 173 174 175 176

<ruby>
class Person < ActiveRecord::Base
  validates_acceptance_of :terms_of_service
end
</ruby>

P
Pratik Naik 已提交
177
The default error message for +validates_acceptance_of+ is "_must be accepted_".
178 179 180 181 182 183 184 185 186

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

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

P
Pratik Naik 已提交
187
h4. +validates_associated+
188 189 190 191 192 193 194 195 196 197

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.

<ruby>
class Library < ActiveRecord::Base
  has_many :books
  validates_associated :books
end
</ruby>

P
Pratik Naik 已提交
198
This validation will work with all of the association types.
199

200
CAUTION: Don't use +validates_associated+ on both ends of your associations. They would call each other in an infinite loop.
201 202 203

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.

P
Pratik Naik 已提交
204
h4. +validates_confirmation_of+
205

P
Pratik Naik 已提交
206
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 whose name is the name of the field that has to be confirmed with "_confirmation" appended.
207 208 209 210 211 212 213 214 215 216 217 218 219 220

<ruby>
class Person < ActiveRecord::Base
  validates_confirmation_of :email
end
</ruby>

In your view template you could use something like

<erb>
<%= text_field :person, :email %>
<%= text_field :person, :email_confirmation %>
</erb>

P
Pratik Naik 已提交
221
This check is performed only if +email_confirmation+ is not +nil+. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at +validates_presence_of+ later on this guide):
222 223 224 225 226 227 228 229

<ruby>
class Person < ActiveRecord::Base
  validates_confirmation_of :email
  validates_presence_of :email_confirmation
end
</ruby>

P
Pratik Naik 已提交
230
The default error message for +validates_confirmation_of+ is "_doesn't match confirmation_".
231

P
Pratik Naik 已提交
232
h4. +validates_exclusion_of+
233 234 235 236

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

<ruby>
P
Pratik Naik 已提交
237
class Account < ActiveRecord::Base
238
  validates_exclusion_of :subdomain, :in => %w(www us ca jp),
239
    :message => "Subdomain %{value} is reserved."
240 241 242
end
</ruby>

243
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 include the attribute's value.
244

245
The default error message for +validates_exclusion_of+ is "_is reserved_".
246

P
Pratik Naik 已提交
247
h4. +validates_format_of+
248

249
This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the +:with+ option.
250 251 252

<ruby>
class Product < ActiveRecord::Base
P
Pratik Naik 已提交
253
  validates_format_of :legacy_code, :with => /\A[a-zA-Z]+\z/,
254 255 256 257 258 259
    :message => "Only letters allowed"
end
</ruby>

The default error message for +validates_format_of+ is "_is invalid_".

P
Pratik Naik 已提交
260
h4. +validates_inclusion_of+
261 262 263 264 265 266

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

<ruby>
class Coffee < ActiveRecord::Base
  validates_inclusion_of :size, :in => %w(small medium large),
267
    :message => "%{value} is not a valid size"
268 269 270
end
</ruby>

P
Pratik Naik 已提交
271
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 include the attribute's value.
272

273
The default error message for +validates_inclusion_of+ is "_is not included in the list_".
274

P
Pratik Naik 已提交
275
h4. +validates_length_of+
276

P
Pratik Naik 已提交
277
This helper validates the length of the attributes' values. It provides a variety of options, so you can specify length constraints in different ways:
278 279 280 281 282 283 284 285 286 287 288 289 290 291

<ruby>
class Person < ActiveRecord::Base
  validates_length_of :name, :minimum => 2
  validates_length_of :bio, :maximum => 500
  validates_length_of :password, :in => 6..20
  validates_length_of :registration_number, :is => 6
end
</ruby>

The possible length constraint options are:

* +:minimum+ - The attribute cannot have less than the specified length.
* +:maximum+ - The attribute cannot have more than the specified length.
P
Pratik Naik 已提交
292 293
* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a range.
* +:is+ - The attribute length must be equal to the given value.
294

295
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 <tt>%{count}</tt> 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.
296 297 298

<ruby>
class Person < ActiveRecord::Base
P
Pratik Naik 已提交
299
  validates_length_of :bio, :maximum => 1000,
300
    :too_long => "%{count} characters is the maximum allowed"
P
Pratik Naik 已提交
301 302 303 304 305 306 307 308 309 310 311
end
</ruby>

This helper counts characters by default, but you can split the value in a different way using the +:tokenizer+ option:

<ruby>
class Essay < ActiveRecord::Base
  validates_length_of :content,
    :minimum   => 300,
    :maximum   => 400,
    :tokenizer => lambda { |str| str.scan(/\w+/) },
312 313
    :too_short => "must have at least %{count} words",
    :too_long  => "must have at most %{count} words"
314 315 316 317 318
end
</ruby>

The +validates_size_of+ helper is an alias for +validates_length_of+.

P
Pratik Naik 已提交
319
h4. +validates_numericality_of+
320

P
Pratik Naik 已提交
321
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.
322

P
Pratik Naik 已提交
323 324 325 326 327 328 329 330 331
If you set +:only_integer+ to +true+, then it will use the

<ruby>
/\A[+-]?\d+\Z/
</ruby>

regular expression to validate the attribute's value. Otherwise, it will try to convert the value to a number using +Float+.

WARNING. Note that the regular expression above allows a trailing newline character.
332 333 334 335 336 337 338 339 340 341

<ruby>
class Player < ActiveRecord::Base
  validates_numericality_of :points
  validates_numericality_of :games_played, :only_integer => true
end
</ruby>

Besides +:only_integer+, the +validates_numericality_of+ helper also accepts the following options to add constraints to acceptable values:

342 343 344 345
* +:greater_than+ - Specifies the value must be greater than the supplied value. The default error message for this option is "_must be greater than %{count}_".
* +:greater_than_or_equal_to+ - Specifies the value must be greater than or equal to the supplied value. The default error message for this option is "_must be greater than or equal to %{count}_".
* +:equal_to+ - Specifies the value must be equal to the supplied value. The default error message for this option is "_must be equal to %{count}_".
* +:less_than+ - Specifies the value must be less than the supplied value. The default error message for this option is "_must be less than %{count}_".
346
* +:less_than_or_equal_to+ - Specifies the value must be less than or equal the supplied value. The default error message for this option is "_must be less than or equal to %{count}_".
P
Pratik Naik 已提交
347 348
* +: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_".
349 350 351

The default error message for +validates_numericality_of+ is "_is not a number_".

P
Pratik Naik 已提交
352
h4. +validates_presence_of+
353

P
Pratik Naik 已提交
354
This helper validates that the specified attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or a blank string, that is, a string that is either empty or consists of whitespace.
355 356 357

<ruby>
class Person < ActiveRecord::Base
358
  validates :name, :login, :email, :presence => true
359 360 361
end
</ruby>

P
Pratik Naik 已提交
362
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.
363 364 365 366 367 368 369 370

<ruby>
class LineItem < ActiveRecord::Base
  belongs_to :order
  validates_presence_of :order_id
end
</ruby>

371
Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use +validates_inclusion_of :field_name, :in => [true, false]+.
372 373 374

The default error message for +validates_presence_of+ is "_can't be empty_".

P
Pratik Naik 已提交
375
h4. +validates_uniqueness_of+
376

377
This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint in the 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 a unique index in your database.
378 379 380 381 382 383 384

<ruby>
class Account < ActiveRecord::Base
  validates_uniqueness_of :email
end
</ruby>

385
The validation happens by performing an SQL query into the model's table, searching for an existing record with the same value in that attribute.
386 387 388 389 390 391

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

<ruby>
class Holiday < ActiveRecord::Base
  validates_uniqueness_of :name, :scope => :year,
P
Pratik Naik 已提交
392
    :message => "should happen once per year"
393 394 395 396 397 398 399 400 401 402 403
end
</ruby>

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.

<ruby>
class Person < ActiveRecord::Base
  validates_uniqueness_of :name, :case_sensitive => false
end
</ruby>

P
Pratik Naik 已提交
404 405
WARNING. Note that some databases are configured to perform case-insensitive searches anyway.

406 407
The default error message for +validates_uniqueness_of+ is "_has already been taken_".

P
Pratik Naik 已提交
408 409 410 411 412 413 414 415 416
h4. +validates_with+

This helper passes the record to a separate class for validation.

<ruby>
class Person < ActiveRecord::Base
  validates_with GoodnessValidator
end

417
class GoodnessValidator < ActiveModel::Validator
P
Pratik Naik 已提交
418 419 420 421 422 423 424 425
  def validate
    if record.first_name == "Evil"
      record.errors[:base] << "This person is evil"
    end
  end
end
</ruby>

426
The +validates_with+ helper takes a class, or a list of classes to use for validation. There is no default error message for +validates_with+. You must manually add errors to the record's errors collection in the validator class.
P
Pratik Naik 已提交
427 428 429 430 431 432

The validator class has two attributes by default:

* +record+ - the record to be validated
* +options+ - the extra options that were passed to +validates_with+

433
Like all other validations, +validates_with+ takes the +:if+, +:unless+ and +:on+ options. If you pass any other options, it will send those options to the validator class as +options+:
P
Pratik Naik 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

<ruby>
class Person < ActiveRecord::Base
  validates_with GoodnessValidator, :fields => [:first_name, :last_name]
end

class GoodnessValidator < ActiveRecord::Validator
  def validate
    if options[:fields].any?{|field| record.send(field) == "Evil" }
      record.errors[:base] << "This person is evil"
    end
  end
end
</ruby>

P
Pratik Naik 已提交
449
h4. +validates_each+
450 451 452 453 454 455

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.

<ruby>
class Person < ActiveRecord::Base
  validates_each :name, :surname do |model, attr, value|
P
Pratik Naik 已提交
456
    model.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
457 458 459 460 461 462 463 464
  end
end
</ruby>

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.

h3. Common Validation Options

P
Pratik Naik 已提交
465
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.
466

P
Pratik Naik 已提交
467
h4. +:allow_nil+
468

P
Pratik Naik 已提交
469
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.
470 471 472 473

<ruby>
class Coffee < ActiveRecord::Base
  validates_inclusion_of :size, :in => %w(small medium large),
474
    :message => "%{value} is not a valid size", :allow_nil => true
475 476 477
end
</ruby>

P
Pratik Naik 已提交
478
h4. +:allow_blank+
479

P
Pratik Naik 已提交
480
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.
481 482 483 484 485 486 487 488 489 490

<ruby>
class Topic < ActiveRecord::Base
  validates_length_of :title, :is => 5, :allow_blank => true
end

Topic.create("title" => "").valid? # => true
Topic.create("title" => nil).valid? # => true
</ruby>

P
Pratik Naik 已提交
491
h4. +:message+
492

P
Pratik Naik 已提交
493
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.
494

P
Pratik Naik 已提交
495
h4. +:on+
496

497
The +:on+ option lets you specify when the validation should happen. The default behavior for all the built-in validation helpers is to be run 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.
498 499 500

<ruby>
class Person < ActiveRecord::Base
P
Pratik Naik 已提交
501
  # it will be possible to update email with a duplicated value
502 503
  validates_uniqueness_of :email, :on => :create

P
Pratik Naik 已提交
504
  # it will be possible to create the record with a non-numerical age
505 506
  validates_numericality_of :age, :on => :update

P
Pratik Naik 已提交
507
  # the default (validates on both create and update)
508
  validates :name, :presence => true, :on => :save
509 510 511
end
</ruby>

P
Pratik Naik 已提交
512
h3. Conditional Validation
513

P
Pratik Naik 已提交
514
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.
515

P
Pratik Naik 已提交
516
h4. Using a Symbol with +:if+ and +:unless+
517 518 519 520 521 522 523 524 525 526 527 528 529

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.

<ruby>
class Order < ActiveRecord::Base
  validates_presence_of :card_number, :if => :paid_with_card?

  def paid_with_card?
    payment_type == "card"
  end
end
</ruby>

P
Pratik Naik 已提交
530
h4. Using a String with +:if+ and +:unless+
531

P
Pratik Naik 已提交
532
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.
533 534 535 536 537 538 539

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

P
Pratik Naik 已提交
540
h4. Using a Proc with +:if+ and +:unless+
541

P
Pratik Naik 已提交
542
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.
543 544 545 546 547 548 549 550

<ruby>
class Account < ActiveRecord::Base
  validates_confirmation_of :password,
    :unless => Proc.new { |a| a.password.blank? }
end
</ruby>

P
Pratik Naik 已提交
551
h3. Creating Custom Validation Methods
552

553
When the built-in validation helpers are not enough for your needs, you can write your own validation methods.
P
Pratik Naik 已提交
554

555
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.
P
Pratik Naik 已提交
556

P
Pratik Naik 已提交
557
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.
558 559 560 561

<ruby>
class Invoice < ActiveRecord::Base
  validate :expiration_date_cannot_be_in_the_past,
P
Pratik Naik 已提交
562
    :discount_cannot_be_greater_than_total_value
563 564 565 566 567 568 569

  def expiration_date_cannot_be_in_the_past
    errors.add(:expiration_date, "can't be in the past") if
      !expiration_date.blank? and expiration_date < Date.today
  end

  def discount_cannot_be_greater_than_total_value
P
Pratik Naik 已提交
570 571
    errors.add(:discount, "can't be greater than total value") if
      discount > total_value
572 573 574 575
  end
end
</ruby>

576
You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find it useful to express that a certain field corresponds to a set of choices:
577 578

<ruby>
P
Pratik Naik 已提交
579
ActiveRecord::Base.class_eval do
P
Pratik Naik 已提交
580
  def self.validates_as_choice(attr_name, n, options={})
P
Pratik Naik 已提交
581
    validates_inclusion_of attr_name, {:in => 1..n}.merge(options)
582 583 584 585
  end
end
</ruby>

P
Pratik Naik 已提交
586
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:
587 588

<ruby>
P
Pratik Naik 已提交
589
class Movie < ActiveRecord::Base
P
Pratik Naik 已提交
590
  validates_as_choice :rating, 5
591 592 593
end
</ruby>

P
Pratik Naik 已提交
594
h3. Working with Validation Errors
595

596
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.
597

P
Pratik Naik 已提交
598
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.
599

600
h4(#working_with_validation_errors-errors). +errors+
P
Pratik Naik 已提交
601

602
Returns an OrderedHash with all errors. Each key is the attribute name and the value is an array of strings with all errors.
603 604 605

<ruby>
class Person < ActiveRecord::Base
606
  validates :name, :presence => true
607 608 609 610 611 612 613
  validates_length_of :name, :minimum => 3
end

person = Person.new
person.valid? # => false
person.errors
 # => {:name => ["can't be blank", "is too short (minimum is 3 characters)"]}
614

615 616 617 618 619
person = Person.new(:name => "John Doe")
person.valid? # => true
person.errors # => []
</ruby>

620
h4(#working_with_validation_errors-errors-2). +errors[]+
621

622
+errors[]+ is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array.
623 624 625

<ruby>
class Person < ActiveRecord::Base
626
  validates :name, :presence => true
627
  validates_length_of :name, :minimum => 3
628
end
629 630 631 632 633 634 635 636 637 638 639 640 641

person = Person.new(:name => "John Doe")
person.valid? # => true
person.errors[:name] # => []

person = Person.new(:name => "JD")
person.valid? # => false
person.errors[:name] # => ["is too short (minimum is 3 characters)"]

person = Person.new
person.valid? # => false
person.errors[:name]
 # => ["can't be blank", "is too short (minimum is 3 characters)"]
642 643
</ruby>

P
Pratik Naik 已提交
644
h4. +errors.add+
P
Pratik Naik 已提交
645

646
The +add+ method lets you manually add messages that are related to particular attributes. You can use the +errors.full_messages+ or +errors.to_a+ methods 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.
647 648 649 650

<ruby>
class Person < ActiveRecord::Base
  def a_method_used_for_validation_purposes
P
Pratik Naik 已提交
651
    errors.add(:name, "cannot contain the characters !@#%*()_-+=")
652 653 654
  end
end

P
Pratik Naik 已提交
655
person = Person.create(:name => "!@#")
656

657 658
person.errors[:name]
 # => ["cannot contain the characters !@#%*()_-+="]
659

P
Pratik Naik 已提交
660
person.errors.full_messages
P
Pratik Naik 已提交
661
 # => ["Name cannot contain the characters !@#%*()_-+="]
662
</ruby>
663

664
Another way to do this is using +[]=+ setter
665

666 667 668 669 670 671
<ruby>
  class Person < ActiveRecord::Base
    def a_method_used_for_validation_purposes
      errors[:name] = "cannot contain the characters !@#%*()_-+="
    end
  end
P
Pratik Naik 已提交
672

673 674 675 676 677 678 679 680 681 682 683
  person = Person.create(:name => "!@#")

  person.errors[:name]
   # => ["cannot contain the characters !@#%*()_-+="]

  person.errors.to_a
   # => ["Name cannot contain the characters !@#%*()_-+="]
</ruby>

h4. +errors[:base]+

684
You can add error 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. Since +errors[:base]+ is an array, you can simply add a string to the array and uses it as the error message.
685 686 687

<ruby>
class Person < ActiveRecord::Base
688 689 690
  def a_method_used_for_validation_purposes
    errors[:base] << "This person is invalid because ..."
  end
691
end
692
</ruby>
693 694 695



P
Pratik Naik 已提交
696
h4. +errors.clear+
P
Pratik Naik 已提交
697

P
Pratik Naik 已提交
698
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.
699 700 701

<ruby>
class Person < ActiveRecord::Base
702
  validates :name, :presence => true
703 704 705 706 707
  validates_length_of :name, :minimum => 3
end

person = Person.new
person.valid? # => false
708
person.errors[:name]
P
Pratik Naik 已提交
709
 # => ["can't be blank", "is too short (minimum is 3 characters)"]
710 711 712

person.errors.clear
person.errors.empty? # => true
P
Pratik Naik 已提交
713

714
p.save # => false
P
Pratik Naik 已提交
715

716
p.errors[:name]
P
Pratik Naik 已提交
717
 # => ["can't be blank", "is too short (minimum is 3 characters)"]
718 719
</ruby>

P
Pratik Naik 已提交
720
h4. +errors.size+
P
Pratik Naik 已提交
721

P
Pratik Naik 已提交
722
The +size+ method returns the total number of error messages for the object.
P
Pratik Naik 已提交
723 724 725

<ruby>
class Person < ActiveRecord::Base
726
  validates :name, :presence => true
P
Pratik Naik 已提交
727 728
  validates_length_of   :name, :minimum => 3
  validates_presence_of :email
P
Pratik Naik 已提交
729 730 731 732
end

person = Person.new
person.valid? # => false
P
Pratik Naik 已提交
733 734 735 736 737
person.errors.size # => 3

person = Person.new(:name => "Andrea", :email => "andrea@example.com")
person.valid? # => true
person.errors.size # => 0
P
Pratik Naik 已提交
738 739 740 741
</ruby>

h3. Displaying Validation Errors in the View

742
Rails provides built-in helpers to display the error messages of your models in your view templates.
743

P
Pratik Naik 已提交
744
h4. +error_messages+ and +error_messages_for+
745

P
Pratik Naik 已提交
746
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.
747 748 749 750 751 752 753 754 755

<ruby>
class Product < ActiveRecord::Base
  validates_presence_of :description, :value
  validates_numericality_of :value, :allow_nil => true
end
</ruby>

<erb>
756
<%= form_for(@product) do |f| %>
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
  <%= f.error_messages %>
  <p>
    <%= f.label :description %><br />
    <%= f.text_field :description %>
  </p>
  <p>
    <%= f.label :value %><br />
    <%= f.text_field :value %>
  </p>
  <p>
    <%= f.submit "Create" %>
  </p>
<% end %>
</erb>

P
Pratik Naik 已提交
772 773
To get the idea, if you submit the form with empty fields you typically get this back, though styles are indeed missing by default:

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
!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.

<erb>
<%= error_messages_for :product %>
</erb>

The displayed text for each error message will always be formed by the capitalized name of the attribute that holds the error, followed by the error message itself.

Both the +form.error_messages+ and the +error_messages_for+ helpers accept options that let you customize the +div+ element that holds the messages, changing the header text, the message below the header text and the tag used for the element that defines the header.

<erb>
<%= f.error_messages :header_message => "Invalid product!",
  :message => "You'll need to fix the following fields:",
  :header_tag => :h3 %>
</erb>

792
Which results in the following content:
793 794 795 796 797

!images/customized_error_messages.png(Customized error messages)!

If you pass +nil+ to any of these options, it will get rid of the respective section of the +div+.

P
Pratik Naik 已提交
798 799
h4. Customizing the Error Messages CSS

P
Pratik Naik 已提交
800
The selectors to customize the style of error messages are:
801

802
* +.field_with_errors+ - Style for the form fields and labels with errors.
803 804 805
* +#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.
P
Pratik Naik 已提交
806 807 808 809 810
* +#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.
811

P
Pratik Naik 已提交
812 813
h4. Customizing the Error Messages HTML

814
By default, form fields with errors are displayed enclosed by a +div+ element with the +field_with_errors+ CSS class. However, it's possible to override that.
P
Pratik Naik 已提交
815 816 817 818 819

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+.
820

P
Pratik Naik 已提交
821
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.
822 823 824 825

<ruby>
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  if instance.error_message.kind_of?(Array)
P
Pratik Naik 已提交
826
    %(#{html_tag}<span class="validation-error">&nbsp;
827
      #{instance.error_message.join(',')}</span>).html_safe
828
  else
P
Pratik Naik 已提交
829
    %(#{html_tag}<span class="validation-error">&nbsp;
830
      #{instance.error_message}</span>).html_safe
831 832 833 834
  end
end
</ruby>

P
Pratik Naik 已提交
835
This will result in something like the following:
836 837 838

!images/validation_error_messages.png(Validation error messages)!

P
Pratik Naik 已提交
839
h3. Callbacks Overview
840

841
Callbacks are methods that get called at certain moments of an object's life cycle. 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.
842

P
Pratik Naik 已提交
843
h4. Callback Registration
844

P
Pratik Naik 已提交
845
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.
846 847 848 849 850 851 852 853 854

<ruby>
class User < ActiveRecord::Base
  validates_presence_of :login, :email

  before_validation :ensure_login_has_a_value

  protected
  def ensure_login_has_a_value
P
Pratik Naik 已提交
855
    if login.nil?
856 857 858 859 860 861
      self.login = email unless email.blank?
    end
  end
end
</ruby>

P
Pratik Naik 已提交
862
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.
863 864 865 866 867

<ruby>
class User < ActiveRecord::Base
  validates_presence_of :login, :email

868
  before_create {|user| user.name = user.login.capitalize
P
Pratik Naik 已提交
869
	if user.name.blank?}
870 871 872
end
</ruby>

P
Pratik Naik 已提交
873
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.
874

P
Pratik Naik 已提交
875 876 877 878 879 880 881 882 883
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 an Object

* +before_validation+
* +after_validation+
* +before_save+
884
* +after_save+
P
Pratik Naik 已提交
885
* +before_create+
886
* +around_create+
P
Pratik Naik 已提交
887 888 889 890 891 892 893
* +after_create+

h4. Updating an Object

* +before_validation+
* +after_validation+
* +before_save+
894
* +after_save+
P
Pratik Naik 已提交
895
* +before_update+
896
* +around_update+
P
Pratik Naik 已提交
897 898 899 900 901 902
* +after_update+

h4. Destroying an Object

* +before_destroy+
* +after_destroy+
903
* +around_destroy+
P
Pratik Naik 已提交
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969

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. +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. 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
  def after_initialize
    puts "You have initialized an object!"
  end

  def after_find
    puts "You have found an object!"
  end
end

>> User.new
You have initialized an object!
=> #<User id: nil>

>> User.first
You have found an object!
You have initialized an object!
=> #<User id: 1>
</ruby>

h3. Running Callbacks

The following methods trigger callbacks:

* +create+
* +create!+
* +decrement!+
* +destroy+
* +destroy_all+
* +increment!+
* +save+
* +save!+
* +save(false)+
* +toggle!+
* +update+
* +update_attribute+
* +update_attributes+
* +update_attributes!+
* +valid?+

Additionally, the +after_find+ callback is triggered by the following finder methods:

* +all+
* +first+
* +find+
* +find_all_by_<em>attribute</em>+
* +find_by_<em>attribute</em>+
* +find_by_<em>attribute</em>!+
* +last+

The +after_initialize+ callback is triggered every time a new object of the class is initialized.

h3. Skipping Callbacks

970
Just as with validations, it's also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.
P
Pratik Naik 已提交
971 972 973 974 975 976 977 978 979 980 981 982 983 984

* +decrement+
* +decrement_counter+
* +delete+
* +delete_all+
* +find_by_sql+
* +increment+
* +increment_counter+
* +toggle+
* +update_all+
* +update_counters+

h3. Halting Execution

985
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.
P
Pratik Naik 已提交
986

987
The whole callback chain is wrapped in a transaction. If any <em>before</em> callback method returns exactly +false+ or raises an exception the execution chain gets halted and a ROLLBACK is issued; <em>after</em> callbacks can only accomplish that by raising an exception.
P
Pratik Naik 已提交
988 989 990 991 992

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

993
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.
P
Pratik Naik 已提交
994 995 996

<ruby>
class User < ActiveRecord::Base
997
  has_many :posts, :dependent => :destroy
P
Pratik Naik 已提交
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
end

class Post < ActiveRecord::Base
  after_destroy :log_destroy_action

  def log_destroy_action
    puts 'Post destroyed'
  end
end

>> user = User.first
=> #<User id: 1>
>> user.posts.create!
=> #<Post id: 1, user_id: 1>
>> user.destroy
Post destroyed
=> #<User id: 1>
</ruby>

P
Pratik Naik 已提交
1017
h3. Conditional Callbacks
1018

P
Pratik Naik 已提交
1019
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.
1020

P
Pratik Naik 已提交
1021
h4. Using +:if+ and +:unless+ with a Symbol
1022

1023
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. When using the +:if+ option, the callback won't be executed if the method returns false; when using the +:unless+ option, the callback won't be executed if the method returns true. 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.
1024 1025 1026 1027 1028 1029 1030

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

P
Pratik Naik 已提交
1031
h4. Using +:if+ and +:unless+ with a String
1032

P
Pratik Naik 已提交
1033
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.
1034 1035 1036 1037 1038 1039 1040

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

P
Pratik Naik 已提交
1041
h4. Using +:if+ and +:unless+ with a Proc
1042

P
Pratik Naik 已提交
1043
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.
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062

<ruby>
class Order < ActiveRecord::Base
  before_save :normalize_card_number,
    :if => Proc.new { |order| order.paid_with_card? }
end
</ruby>

h4. Multiple Conditions for Callbacks

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

<ruby>
class Comment < ActiveRecord::Base
  after_create :send_email_to_author, :if => :author_wants_emails?,
    :unless => Proc.new { |comment| comment.post.ignore_comments? }
end
</ruby>

P
Pratik Naik 已提交
1063
h3. Callback Classes
1064

P
Pratik Naik 已提交
1065
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.
1066

P
Pratik Naik 已提交
1067
Here's an example where we create a class with an +after_destroy+ callback for a +PictureFile+ model.
1068 1069 1070 1071

<ruby>
class PictureFileCallbacks
  def after_destroy(picture_file)
1072
    File.delete(picture_file.filepath)
P
Pratik Naik 已提交
1073
      if File.exists?(picture_file.filepath)
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
  end
end
</ruby>

When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way:

<ruby>
class PictureFile < ActiveRecord::Base
  after_destroy PictureFileCallbacks.new
end
</ruby>

P
Pratik Naik 已提交
1086
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.
1087 1088 1089 1090

<ruby>
class PictureFileCallbacks
  def self.after_destroy(picture_file)
1091
    File.delete(picture_file.filepath)
P
Pratik Naik 已提交
1092
      if File.exists?(picture_file.filepath)
1093 1094 1095 1096
  end
end
</ruby>

P
Pratik Naik 已提交
1097
If the callback method is declared this way, it won't be necessary to instantiate a +PictureFileCallbacks+ object.
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108

<ruby>
class PictureFile < ActiveRecord::Base
  after_destroy PictureFileCallbacks
end
</ruby>

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

h3. Observers

P
Pratik Naik 已提交
1109
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.
1110

P
Pratik Naik 已提交
1111
h4. Creating Observers
1112

P
Pratik Naik 已提交
1113
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.
1114

1115 1116 1117 1118
<shell>
rails generate observer User
</shell>

1119
<ruby>
P
Pratik Naik 已提交
1120
class UserObserver < ActiveRecord::Observer
1121
  def after_create(model)
P
Pratik Naik 已提交
1122
    # code to send confirmation email...
1123 1124 1125 1126
  end
end
</ruby>

P
Pratik Naik 已提交
1127
As with callback classes, the observer's methods receive the observed model as a parameter.
1128

P
Pratik Naik 已提交
1129
h4. Registering Observers
1130

1131
Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/application.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/application.rb+ this way:
1132 1133 1134

<ruby>
# Activate observers that should always be running
P
Pratik Naik 已提交
1135
config.active_record.observers = :user_observer
1136 1137
</ruby>

1138
As usual, settings in +config/environments+ take precedence over those in +config/application.rb+. So, if you prefer that an observer doesn't run in all environments, you can simply register it in a specific environment instead.
P
Pratik Naik 已提交
1139 1140

h4. Sharing Observers
1141

P
Pratik Naik 已提交
1142
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.
1143

P
Pratik Naik 已提交
1144 1145 1146
<ruby>
class MailerObserver < ActiveRecord::Observer
  observe :registration, :user
1147

P
Pratik Naik 已提交
1148 1149 1150 1151 1152
  def after_create(model)
    # code to send confirmation email...
  end
end
</ruby>
1153

1154
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/application.rb+ in order to take effect.
1155

P
Pratik Naik 已提交
1156 1157 1158 1159
<ruby>
# Activate observers that should always be running
config.active_record.observers = :mailer_observer
</ruby>
1160 1161 1162

h3. Changelog

1163
* July 20, 2010: Fixed typos and rephrased some paragraphs for clarity. "Jaime Iniesta":http://jaimeiniesta.com
1164
* May 24, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
1165
* May 15, 2010: Validation Errors section updated by "Emili Parreño":http://www.eparreno.com
P
Pratik Naik 已提交
1166
* March 7, 2009: Callbacks revision by Trevor Turk
P
Pratik Naik 已提交
1167 1168 1169
* 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