rails 2.3.8 → 2.3.9.pre

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

Files changed (119) hide show
  1. data/CHANGELOG +3 -2
  2. data/Rakefile +6 -7
  3. data/builtin/rails_info/rails/info.rb +1 -1
  4. data/environments/boot.rb +6 -2
  5. data/environments/environment.rb +1 -1
  6. data/lib/initializer.rb +44 -20
  7. data/lib/rails/plugin.rb +1 -1
  8. data/lib/rails/plugin/loader.rb +3 -3
  9. data/lib/rails/version.rb +1 -1
  10. data/lib/rails_generator/generators/components/migration/migration_generator.rb +1 -1
  11. data/lib/rails_generator/generators/components/plugin/templates/test_helper.rb +2 -1
  12. metadata +25 -124
  13. data/guides/files/javascripts/code_highlighter.js +0 -188
  14. data/guides/files/javascripts/guides.js +0 -8
  15. data/guides/files/javascripts/highlighters.js +0 -90
  16. data/guides/files/stylesheets/main.css +0 -441
  17. data/guides/files/stylesheets/print.css +0 -52
  18. data/guides/files/stylesheets/reset.css +0 -43
  19. data/guides/files/stylesheets/style.css +0 -13
  20. data/guides/files/stylesheets/syntax.css +0 -31
  21. data/guides/images/belongs_to.png +0 -0
  22. data/guides/images/book_icon.gif +0 -0
  23. data/guides/images/bullet.gif +0 -0
  24. data/guides/images/chapters_icon.gif +0 -0
  25. data/guides/images/check_bullet.gif +0 -0
  26. data/guides/images/credits_pic_blank.gif +0 -0
  27. data/guides/images/csrf.png +0 -0
  28. data/guides/images/customized_error_messages.png +0 -0
  29. data/guides/images/error_messages.png +0 -0
  30. data/guides/images/feature_tile.gif +0 -0
  31. data/guides/images/footer_tile.gif +0 -0
  32. data/guides/images/fxn.jpg +0 -0
  33. data/guides/images/grey_bullet.gif +0 -0
  34. data/guides/images/habtm.png +0 -0
  35. data/guides/images/has_many.png +0 -0
  36. data/guides/images/has_many_through.png +0 -0
  37. data/guides/images/has_one.png +0 -0
  38. data/guides/images/has_one_through.png +0 -0
  39. data/guides/images/header_backdrop.png +0 -0
  40. data/guides/images/header_tile.gif +0 -0
  41. data/guides/images/i18n/demo_localized_pirate.png +0 -0
  42. data/guides/images/i18n/demo_translated_en.png +0 -0
  43. data/guides/images/i18n/demo_translated_pirate.png +0 -0
  44. data/guides/images/i18n/demo_translation_missing.png +0 -0
  45. data/guides/images/i18n/demo_untranslated.png +0 -0
  46. data/guides/images/icons/README +0 -5
  47. data/guides/images/icons/callouts/1.png +0 -0
  48. data/guides/images/icons/callouts/10.png +0 -0
  49. data/guides/images/icons/callouts/11.png +0 -0
  50. data/guides/images/icons/callouts/12.png +0 -0
  51. data/guides/images/icons/callouts/13.png +0 -0
  52. data/guides/images/icons/callouts/14.png +0 -0
  53. data/guides/images/icons/callouts/15.png +0 -0
  54. data/guides/images/icons/callouts/2.png +0 -0
  55. data/guides/images/icons/callouts/3.png +0 -0
  56. data/guides/images/icons/callouts/4.png +0 -0
  57. data/guides/images/icons/callouts/5.png +0 -0
  58. data/guides/images/icons/callouts/6.png +0 -0
  59. data/guides/images/icons/callouts/7.png +0 -0
  60. data/guides/images/icons/callouts/8.png +0 -0
  61. data/guides/images/icons/callouts/9.png +0 -0
  62. data/guides/images/icons/caution.png +0 -0
  63. data/guides/images/icons/example.png +0 -0
  64. data/guides/images/icons/home.png +0 -0
  65. data/guides/images/icons/important.png +0 -0
  66. data/guides/images/icons/next.png +0 -0
  67. data/guides/images/icons/note.png +0 -0
  68. data/guides/images/icons/prev.png +0 -0
  69. data/guides/images/icons/tip.png +0 -0
  70. data/guides/images/icons/up.png +0 -0
  71. data/guides/images/icons/warning.png +0 -0
  72. data/guides/images/nav_arrow.gif +0 -0
  73. data/guides/images/polymorphic.png +0 -0
  74. data/guides/images/posts_index.png +0 -0
  75. data/guides/images/rails_guides_logo.gif +0 -0
  76. data/guides/images/rails_logo_remix.gif +0 -0
  77. data/guides/images/rails_welcome.png +0 -0
  78. data/guides/images/session_fixation.png +0 -0
  79. data/guides/images/tab_grey.gif +0 -0
  80. data/guides/images/tab_info.gif +0 -0
  81. data/guides/images/tab_note.gif +0 -0
  82. data/guides/images/tab_red.gif +0 -0
  83. data/guides/images/tab_yellow.gif +0 -0
  84. data/guides/images/tab_yellow.png +0 -0
  85. data/guides/images/validation_error_messages.png +0 -0
  86. data/guides/rails_guides.rb +0 -42
  87. data/guides/rails_guides/generator.rb +0 -138
  88. data/guides/rails_guides/helpers.rb +0 -34
  89. data/guides/rails_guides/indexer.rb +0 -55
  90. data/guides/rails_guides/textile_extensions.rb +0 -41
  91. data/guides/source/2_2_release_notes.textile +0 -422
  92. data/guides/source/2_3_release_notes.textile +0 -610
  93. data/guides/source/action_controller_overview.textile +0 -776
  94. data/guides/source/action_mailer_basics.textile +0 -424
  95. data/guides/source/active_record_basics.textile +0 -135
  96. data/guides/source/active_record_querying.textile +0 -969
  97. data/guides/source/activerecord_validations_callbacks.textile +0 -1086
  98. data/guides/source/association_basics.textile +0 -1781
  99. data/guides/source/caching_with_rails.textile +0 -524
  100. data/guides/source/command_line.textile +0 -589
  101. data/guides/source/configuring.textile +0 -234
  102. data/guides/source/contribute.textile +0 -71
  103. data/guides/source/contributing_to_rails.textile +0 -239
  104. data/guides/source/credits.erb.textile +0 -52
  105. data/guides/source/debugging_rails_applications.textile +0 -709
  106. data/guides/source/form_helpers.textile +0 -766
  107. data/guides/source/getting_started.textile +0 -1297
  108. data/guides/source/i18n.textile +0 -912
  109. data/guides/source/index.erb.textile +0 -124
  110. data/guides/source/layout.html.erb +0 -103
  111. data/guides/source/layouts_and_rendering.textile +0 -979
  112. data/guides/source/migrations.textile +0 -591
  113. data/guides/source/nested_model_forms.textile +0 -222
  114. data/guides/source/performance_testing.textile +0 -531
  115. data/guides/source/plugins.textile +0 -1512
  116. data/guides/source/rails_on_rack.textile +0 -309
  117. data/guides/source/routing.textile +0 -903
  118. data/guides/source/security.textile +0 -986
  119. data/guides/source/testing.textile +0 -951
@@ -1,1086 +0,0 @@
1
- h2. Active Record Validations and Callbacks
2
-
3
- This guide teaches you how to hook into the lifecycle of your Active Record objects. You will learn how to validate the state of objects before they go into the database, and how to perform custom operations at certain points in the object lifecycle.
4
-
5
- After reading this guide and trying out the presented concepts, we hope that you'll be able to:
6
-
7
- * Understand the lifecycle of Active Record objects
8
- * Use the built-in Active Record validation helpers
9
- * Create your own custom validation methods
10
- * Work with the error messages generated by the validation process
11
- * Create callback methods that respond to events in the object lifecycle
12
- * Create special classes that encapsulate common behavior for your callbacks
13
- * Create Observers that respond to lifecycle events outside of the original class
14
-
15
- endprologue.
16
-
17
- h3. The Object Lifecycle
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 lifecycle</em> so that you can control your application and its data.
20
-
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
-
23
- h3. Validations Overview
24
-
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
-
27
- h4. Why Use Validations?
28
-
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
-
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
-
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.
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.
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
- h4. When Does Validation Happen?
39
-
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
- <ruby>
43
- class Person < ActiveRecord::Base
44
- end
45
- </ruby>
46
-
47
- We can see how it works by looking at some script/console output:
48
-
49
- <shell>
50
- >> p = Person.new(:name => "John Doe")
51
- => #<Person id: nil, name: "John Doe", created_at: nil, :updated_at: nil>
52
- >> p.new_record?
53
- => true
54
- >> p.save
55
- => true
56
- >> p.new_record?
57
- => false
58
- </shell>
59
-
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
- 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.
63
-
64
- The following methods trigger validations, and will save the object to the database only if the object is valid:
65
-
66
- * +create+
67
- * +create!+
68
- * +save+
69
- * +save!+
70
- * +update+
71
- * +update_attributes+
72
- * +update_attributes!+
73
-
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 object/s.
75
-
76
- h4. Skipping Validations
77
-
78
- The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution.
79
-
80
- * +decrement!+
81
- * +decrement_counter+
82
- * +increment!+
83
- * +increment_counter+
84
- * +toggle!+
85
- * +update_all+
86
- * +update_attribute+
87
- * +update_counters+
88
-
89
- Note that +save+ also has the ability to skip validations if passed +false+ as argument. This technique should be used with caution.
90
-
91
- * +save(false)+
92
-
93
- h4. +valid?+ and +invalid?+
94
-
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
- <ruby>
98
- class Person < ActiveRecord::Base
99
- validates_presence_of :name
100
- end
101
-
102
- Person.create(:name => "John Doe").valid? # => true
103
- Person.create(:name => nil).valid? # => false
104
- </ruby>
105
-
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
-
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
- <ruby>
111
- class Person < ActiveRecord::Base
112
- validates_presence_of :name
113
- end
114
-
115
- >> p = Person.new
116
- => #<Person id: nil, name: nil>
117
- >> p.errors
118
- => #<ActiveRecord::Errors..., @errors={}>
119
-
120
- >> p.valid?
121
- => false
122
- >> p.errors
123
- => #<ActiveRecord::Errors..., @errors={"name"=>["can't be blank"]}>
124
-
125
- >> p = Person.create
126
- => #<Person id: nil, name: nil>
127
- >> p.errors
128
- => #<ActiveRecord::Errors..., @errors={"name"=>["can't be blank"]}>
129
-
130
- >> p.save
131
- => false
132
-
133
- >> p.save!
134
- => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
135
-
136
- >> Person.create!
137
- => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
138
- </ruby>
139
-
140
- +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.
141
-
142
- h4. +errors.invalid?+
143
-
144
- To verify whether or not a particular attribute of an object is valid, you can use the +errors.invalid?+ method. This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +ActiveRecord::Base#invalid?+ method explained above because it doesn't verify the validity of the object as a whole. It only checks to see whether there are errors found on an individual attribute of the object.
145
-
146
- <ruby>
147
- class Person < ActiveRecord::Base
148
- validates_presence_of :name
149
- end
150
-
151
- >> Person.new.errors.invalid?(:name) # => false
152
- >> Person.create.errors.invalid?(:name) # => true
153
- </ruby>
154
-
155
- 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.
156
-
157
- h3. Validation Helpers
158
-
159
- 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.
160
-
161
- 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.
162
-
163
- 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.
164
-
165
- h4. +validates_acceptance_of+
166
-
167
- 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).
168
-
169
- <ruby>
170
- class Person < ActiveRecord::Base
171
- validates_acceptance_of :terms_of_service
172
- end
173
- </ruby>
174
-
175
- The default error message for +validates_acceptance_of+ is "_must be accepted_".
176
-
177
- +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.
178
-
179
- <ruby>
180
- class Person < ActiveRecord::Base
181
- validates_acceptance_of :terms_of_service, :accept => 'yes'
182
- end
183
- </ruby>
184
-
185
- h4. +validates_associated+
186
-
187
- 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.
188
-
189
- <ruby>
190
- class Library < ActiveRecord::Base
191
- has_many :books
192
- validates_associated :books
193
- end
194
- </ruby>
195
-
196
- This validation will work with all of the association types.
197
-
198
- CAUTION: Don't use +validates_associated+ on both ends of your associations, they would call each other in an infinite loop.
199
-
200
- 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.
201
-
202
- h4. +validates_confirmation_of+
203
-
204
- 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.
205
-
206
- <ruby>
207
- class Person < ActiveRecord::Base
208
- validates_confirmation_of :email
209
- end
210
- </ruby>
211
-
212
- In your view template you could use something like
213
-
214
- <erb>
215
- <%= text_field :person, :email %>
216
- <%= text_field :person, :email_confirmation %>
217
- </erb>
218
-
219
- 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):
220
-
221
- <ruby>
222
- class Person < ActiveRecord::Base
223
- validates_confirmation_of :email
224
- validates_presence_of :email_confirmation
225
- end
226
- </ruby>
227
-
228
- The default error message for +validates_confirmation_of+ is "_doesn't match confirmation_".
229
-
230
- h4. +validates_exclusion_of+
231
-
232
- This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.
233
-
234
- <ruby>
235
- class Account < ActiveRecord::Base
236
- validates_exclusion_of :subdomain, :in => %w(www),
237
- :message => "Subdomain {{value}} is reserved."
238
- end
239
- </ruby>
240
-
241
- 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.
242
-
243
- The default error message for +validates_exclusion_of+ is "_is not included in the list_".
244
-
245
- h4. +validates_format_of+
246
-
247
- This helper validates the attributes' values by testing whether they match a given regular expresion, which is specified using the +:with+ option.
248
-
249
- <ruby>
250
- class Product < ActiveRecord::Base
251
- validates_format_of :legacy_code, :with => /\A[a-zA-Z]+\z/,
252
- :message => "Only letters allowed"
253
- end
254
- </ruby>
255
-
256
- The default error message for +validates_format_of+ is "_is invalid_".
257
-
258
- h4. +validates_inclusion_of+
259
-
260
- This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.
261
-
262
- <ruby>
263
- class Coffee < ActiveRecord::Base
264
- validates_inclusion_of :size, :in => %w(small medium large),
265
- :message => "{{value}} is not a valid size"
266
- end
267
- </ruby>
268
-
269
- 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.
270
-
271
- The default error message for +validates_inclusion_of+ is "_is not included in the list_".
272
-
273
- h4. +validates_length_of+
274
-
275
- This helper validates the length of the attributes' values. It provides a variety of options, so you can specify length constraints in different ways:
276
-
277
- <ruby>
278
- class Person < ActiveRecord::Base
279
- validates_length_of :name, :minimum => 2
280
- validates_length_of :bio, :maximum => 500
281
- validates_length_of :password, :in => 6..20
282
- validates_length_of :registration_number, :is => 6
283
- end
284
- </ruby>
285
-
286
- The possible length constraint options are:
287
-
288
- * +:minimum+ - The attribute cannot have less than the specified length.
289
- * +:maximum+ - The attribute cannot have more than the specified length.
290
- * +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a range.
291
- * +:is+ - The attribute length must be equal to the given value.
292
-
293
- 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.
294
-
295
- <ruby>
296
- class Person < ActiveRecord::Base
297
- validates_length_of :bio, :maximum => 1000,
298
- :too_long => "{{count}} characters is the maximum allowed"
299
- end
300
- </ruby>
301
-
302
- This helper counts characters by default, but you can split the value in a different way using the +:tokenizer+ option:
303
-
304
- <ruby>
305
- class Essay < ActiveRecord::Base
306
- validates_length_of :content,
307
- :minimum => 300,
308
- :maximum => 400,
309
- :tokenizer => lambda { |str| str.scan(/\w+/) },
310
- :too_short => "must have at least {{count}} words",
311
- :too_long => "must have at most {{count}} words"
312
- end
313
- </ruby>
314
-
315
- The +validates_size_of+ helper is an alias for +validates_length_of+.
316
-
317
- h4. +validates_numericality_of+
318
-
319
- 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.
320
-
321
- If you set +:only_integer+ to +true+, then it will use the
322
-
323
- <ruby>
324
- /\A[+-]?\d+\Z/
325
- </ruby>
326
-
327
- regular expression to validate the attribute's value. Otherwise, it will try to convert the value to a number using +Float+.
328
-
329
- WARNING. Note that the regular expression above allows a trailing newline character.
330
-
331
- <ruby>
332
- class Player < ActiveRecord::Base
333
- validates_numericality_of :points
334
- validates_numericality_of :games_played, :only_integer => true
335
- end
336
- </ruby>
337
-
338
- Besides +:only_integer+, the +validates_numericality_of+ helper also accepts the following options to add constraints to acceptable values:
339
-
340
- * +: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}}_".
341
- * +: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}}".
342
- * +: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}}_".
343
- * +: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}}_".
344
- * +: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 or equal to {{count}}_".
345
- * +:odd+ - Specifies the value must be an odd number if set to true. The default error message for this option is "_must be odd_".
346
- * +:even+ - Specifies the value must be an even number if set to true. The default error message for this option is "_must be even_".
347
-
348
- The default error message for +validates_numericality_of+ is "_is not a number_".
349
-
350
- h4. +validates_presence_of+
351
-
352
- 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.
353
-
354
- <ruby>
355
- class Person < ActiveRecord::Base
356
- validates_presence_of :name, :login, :email
357
- end
358
- </ruby>
359
-
360
- 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.
361
-
362
- <ruby>
363
- class LineItem < ActiveRecord::Base
364
- belongs_to :order
365
- validates_presence_of :order_id
366
- end
367
- </ruby>
368
-
369
- 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]+.
370
-
371
- The default error message for +validates_presence_of+ is "_can't be empty_".
372
-
373
- h4. +validates_uniqueness_of+
374
-
375
- 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 an unique index in your database.
376
-
377
- <ruby>
378
- class Account < ActiveRecord::Base
379
- validates_uniqueness_of :email
380
- end
381
- </ruby>
382
-
383
- The validation happens by performing a SQL query into the model's table, searching for an existing record with the same value in that attribute.
384
-
385
- There is a +:scope+ option that you can use to specify other attributes that are used to limit the uniqueness check:
386
-
387
- <ruby>
388
- class Holiday < ActiveRecord::Base
389
- validates_uniqueness_of :name, :scope => :year,
390
- :message => "should happen once per year"
391
- end
392
- </ruby>
393
-
394
- 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.
395
-
396
- <ruby>
397
- class Person < ActiveRecord::Base
398
- validates_uniqueness_of :name, :case_sensitive => false
399
- end
400
- </ruby>
401
-
402
- WARNING. Note that some databases are configured to perform case-insensitive searches anyway.
403
-
404
- The default error message for +validates_uniqueness_of+ is "_has already been taken_".
405
-
406
- h4. +validates_each+
407
-
408
- 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.
409
-
410
- <ruby>
411
- class Person < ActiveRecord::Base
412
- validates_each :name, :surname do |model, attr, value|
413
- model.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
414
- end
415
- end
416
- </ruby>
417
-
418
- 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.
419
-
420
- h3. Common Validation Options
421
-
422
- 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.
423
-
424
- h4. +:allow_nil+
425
-
426
- 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.
427
-
428
- <ruby>
429
- class Coffee < ActiveRecord::Base
430
- validates_inclusion_of :size, :in => %w(small medium large),
431
- :message => "{{value}} is not a valid size", :allow_nil => true
432
- end
433
- </ruby>
434
-
435
- h4. +:allow_blank+
436
-
437
- 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.
438
-
439
- <ruby>
440
- class Topic < ActiveRecord::Base
441
- validates_length_of :title, :is => 5, :allow_blank => true
442
- end
443
-
444
- Topic.create("title" => "").valid? # => true
445
- Topic.create("title" => nil).valid? # => true
446
- </ruby>
447
-
448
- h4. +:message+
449
-
450
- 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.
451
-
452
- h4. +:on+
453
-
454
- 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.
455
-
456
- <ruby>
457
- class Person < ActiveRecord::Base
458
- # it will be possible to update email with a duplicated value
459
- validates_uniqueness_of :email, :on => :create
460
-
461
- # it will be possible to create the record with a non-numerical age
462
- validates_numericality_of :age, :on => :update
463
-
464
- # the default (validates on both create and update)
465
- validates_presence_of :name, :on => :save
466
- end
467
- </ruby>
468
-
469
- h3. Conditional Validation
470
-
471
- 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.
472
-
473
- h4. Using a Symbol with +:if+ and +:unless+
474
-
475
- 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.
476
-
477
- <ruby>
478
- class Order < ActiveRecord::Base
479
- validates_presence_of :card_number, :if => :paid_with_card?
480
-
481
- def paid_with_card?
482
- payment_type == "card"
483
- end
484
- end
485
- </ruby>
486
-
487
- h4. Using a String with +:if+ and +:unless+
488
-
489
- 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.
490
-
491
- <ruby>
492
- class Person < ActiveRecord::Base
493
- validates_presence_of :surname, :if => "name.nil?"
494
- end
495
- </ruby>
496
-
497
- h4. Using a Proc with +:if+ and +:unless+
498
-
499
- 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.
500
-
501
- <ruby>
502
- class Account < ActiveRecord::Base
503
- validates_confirmation_of :password,
504
- :unless => Proc.new { |a| a.password.blank? }
505
- end
506
- </ruby>
507
-
508
- h3. Creating Custom Validation Methods
509
-
510
- When the built-in validation helpers are not enough for your needs, you can write your own validation methods.
511
-
512
- 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.
513
-
514
- 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.
515
-
516
- <ruby>
517
- class Invoice < ActiveRecord::Base
518
- validate :expiration_date_cannot_be_in_the_past,
519
- :discount_cannot_be_greater_than_total_value
520
-
521
- def expiration_date_cannot_be_in_the_past
522
- errors.add(:expiration_date, "can't be in the past") if
523
- !expiration_date.blank? and expiration_date < Date.today
524
- end
525
-
526
- def discount_cannot_be_greater_than_total_value
527
- errors.add(:discount, "can't be greater than total value") if
528
- discount > total_value
529
- end
530
- end
531
- </ruby>
532
-
533
- You can even create your own validation helpers and reuse them in several different models. Here is an example where we create a custom validation helper to validate the format of fields that represent email addresses:
534
-
535
- <ruby>
536
- ActiveRecord::Base.class_eval do
537
- def self.validates_as_radio(attr_name, n, options={})
538
- validates_inclusion_of attr_name, {:in => 1..n}.merge(options)
539
- end
540
- end
541
- </ruby>
542
-
543
- 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:
544
-
545
- <ruby>
546
- class Movie < ActiveRecord::Base
547
- validates_as_radio :rating, 5
548
- end
549
- </ruby>
550
-
551
- h3. Working with Validation Errors
552
-
553
- 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.
554
-
555
- 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.
556
-
557
- h4. +errors.add_to_base+
558
-
559
- The +add_to_base+ method lets you add errors messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. +add_to_base+ simply receives a string and uses this as the error message.
560
-
561
- <ruby>
562
- class Person < ActiveRecord::Base
563
- def a_method_used_for_validation_purposes
564
- errors.add_to_base("This person is invalid because ...")
565
- end
566
- end
567
- </ruby>
568
-
569
- h4. +errors.add+
570
-
571
- The +add+ method lets you manually add messages that are related to particular attributes. You can use the +full_messages+ method to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). +add+ receives the name of the attribute you want to add the message to, and the message itself.
572
-
573
- <ruby>
574
- class Person < ActiveRecord::Base
575
- def a_method_used_for_validation_purposes
576
- errors.add(:name, "cannot contain the characters !@#%*()_-+=")
577
- end
578
- end
579
-
580
- person = Person.create(:name => "!@#")
581
-
582
- person.errors.on(:name)
583
- # => "cannot contain the characters !@#%*()_-+="
584
-
585
- person.errors.full_messages
586
- # => ["Name cannot contain the characters !@#%*()_-+="]
587
- </ruby>
588
-
589
- h4. +errors.on+
590
-
591
- The +on+ method is used when you want to check the error messages for a specific attribute. It returns different kinds of objects depending on the state of the +errors+ collection for the given attribute. If there are no errors related to the attribute +on+ returns +nil+. If there is just one error message for this attribute +on+ returns a string with the message. When +errors+ holds two or more error messages for the attribute, +on+ returns an array of strings, each one with one error message.
592
-
593
- <ruby>
594
- class Person < ActiveRecord::Base
595
- validates_presence_of :name
596
- validates_length_of :name, :minimum => 3
597
- end
598
-
599
- person = Person.new(:name => "John Doe")
600
- person.valid? # => true
601
- person.errors.on(:name) # => nil
602
-
603
- person = Person.new(:name => "JD")
604
- person.valid? # => false
605
- person.errors.on(:name)
606
- # => "is too short (minimum is 3 characters)"
607
-
608
- person = Person.new
609
- person.valid? # => false
610
- person.errors.on(:name)
611
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
612
- </ruby>
613
-
614
- h4. +errors.clear+
615
-
616
- 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.
617
-
618
- <ruby>
619
- class Person < ActiveRecord::Base
620
- validates_presence_of :name
621
- validates_length_of :name, :minimum => 3
622
- end
623
-
624
- person = Person.new
625
- person.valid? # => false
626
- person.errors.on(:name)
627
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
628
-
629
- person.errors.clear
630
- person.errors.empty? # => true
631
-
632
- p.save # => false
633
-
634
- p.errors.on(:name)
635
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
636
- </ruby>
637
-
638
- h4. +errors.size+
639
-
640
- The +size+ method returns the total number of error messages for the object.
641
-
642
- <ruby>
643
- class Person < ActiveRecord::Base
644
- validates_presence_of :name
645
- validates_length_of :name, :minimum => 3
646
- validates_presence_of :email
647
- end
648
-
649
- person = Person.new
650
- person.valid? # => false
651
- person.errors.size # => 3
652
-
653
- person = Person.new(:name => "Andrea", :email => "andrea@example.com")
654
- person.valid? # => true
655
- person.errors.size # => 0
656
- </ruby>
657
-
658
- h3. Displaying Validation Errors in the View
659
-
660
- Rails provides built-in helpers to display the error messages of your models in your view templates.
661
-
662
- h4. +error_messages+ and +error_messages_for+
663
-
664
- 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.
665
-
666
- <ruby>
667
- class Product < ActiveRecord::Base
668
- validates_presence_of :description, :value
669
- validates_numericality_of :value, :allow_nil => true
670
- end
671
- </ruby>
672
-
673
- <erb>
674
- <% form_for(@product) do |f| %>
675
- <%= f.error_messages %>
676
- <p>
677
- <%= f.label :description %><br />
678
- <%= f.text_field :description %>
679
- </p>
680
- <p>
681
- <%= f.label :value %><br />
682
- <%= f.text_field :value %>
683
- </p>
684
- <p>
685
- <%= f.submit "Create" %>
686
- </p>
687
- <% end %>
688
- </erb>
689
-
690
- To get the idea, if you submit the form with empty fields you typically get this back, though styles are indeed missing by default:
691
-
692
- !images/error_messages.png(Error messages)!
693
-
694
- 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.
695
-
696
- <erb>
697
- <%= error_messages_for :product %>
698
- </erb>
699
-
700
- 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.
701
-
702
- 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.
703
-
704
- <erb>
705
- <%= f.error_messages :header_message => "Invalid product!",
706
- :message => "You'll need to fix the following fields:",
707
- :header_tag => :h3 %>
708
- </erb>
709
-
710
- Which results in the following content
711
-
712
- !images/customized_error_messages.png(Customized error messages)!
713
-
714
- If you pass +nil+ to any of these options, it will get rid of the respective section of the +div+.
715
-
716
- h4. Customizing the Error Messages CSS
717
-
718
- The selectors to customize the style of error messages are:
719
-
720
- * +.fieldWithErrors+ - Style for the form fields and labels with errors.
721
- * +#errorExplanation+ - Style for the +div+ element with the error messages.
722
- * +#errorExplanation h2+ - Style for the header of the +div+ element.
723
- * +#errorExplanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element.
724
- * +#errorExplanation ul li+ - Style for the list items with individual error messages.
725
-
726
- Scaffolding for example generates +public/stylesheets/scaffold.css+, which defines the red-based style you saw above.
727
-
728
- The name of the class and the id can be changed with the +:class+ and +:id+ options, accepted by both helpers.
729
-
730
- h4. Customizing the Error Messages HTML
731
-
732
- By default, form fields with errors are displayed enclosed by a +div+ element with the +fieldWithErrors+ CSS class. However, it's possible to override that.
733
-
734
- The way form fields with errors are treated is defined by +ActionView::Base.field_error_proc+. This is a +Proc+ that receives two parameters:
735
-
736
- * A string with the HTML tag
737
- * An instance of +ActionView::Helpers::InstanceTag+.
738
-
739
- 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.
740
-
741
- <ruby>
742
- ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
743
- if instance.error_message.kind_of?(Array)
744
- %(#{html_tag}<span class="validation-error">&nbsp;
745
- #{instance.error_message.join(',')}</span>)
746
- else
747
- %(#{html_tag}<span class="validation-error">&nbsp;
748
- #{instance.error_message}</span>)
749
- end
750
- end
751
- </ruby>
752
-
753
- This will result in something like the following:
754
-
755
- !images/validation_error_messages.png(Validation error messages)!
756
-
757
- h3. Callbacks Overview
758
-
759
- Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
760
-
761
- h4. Callback Registration
762
-
763
- 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.
764
-
765
- <ruby>
766
- class User < ActiveRecord::Base
767
- validates_presence_of :login, :email
768
-
769
- before_validation :ensure_login_has_a_value
770
-
771
- protected
772
- def ensure_login_has_a_value
773
- if login.nil?
774
- self.login = email unless email.blank?
775
- end
776
- end
777
- end
778
- </ruby>
779
-
780
- 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.
781
-
782
- <ruby>
783
- class User < ActiveRecord::Base
784
- validates_presence_of :login, :email
785
-
786
- before_create {|user| user.name = user.login.capitalize
787
- if user.name.blank?}
788
- end
789
- </ruby>
790
-
791
- 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.
792
-
793
- h3. Available Callbacks
794
-
795
- 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:
796
-
797
- h4. Creating an Object
798
-
799
- * +before_validation+
800
- * +before_validation_on_create+
801
- * +after_validation+
802
- * +after_validation_on_create+
803
- * +before_save+
804
- * +before_create+
805
- * INSERT OPERATION
806
- * +after_create+
807
- * +after_save+
808
-
809
- h4. Updating an Object
810
-
811
- * +before_validation+
812
- * +before_validation_on_update+
813
- * +after_validation+
814
- * +after_validation_on_update+
815
- * +before_save+
816
- * +before_update+
817
- * UPDATE OPERATION
818
- * +after_update+
819
- * +after_save+
820
-
821
- h4. Destroying an Object
822
-
823
- * +before_destroy+
824
- * DELETE OPERATION
825
- * +after_destroy+
826
-
827
- 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.
828
-
829
- h4. +after_initialize+ and +after_find+
830
-
831
- 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.
832
-
833
- 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.
834
-
835
- 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.
836
-
837
- <ruby>
838
- class User < ActiveRecord::Base
839
- def after_initialize
840
- puts "You have initialized an object!"
841
- end
842
-
843
- def after_find
844
- puts "You have found an object!"
845
- end
846
- end
847
-
848
- >> User.new
849
- You have initialized an object!
850
- => #<User id: nil>
851
-
852
- >> User.first
853
- You have found an object!
854
- You have initialized an object!
855
- => #<User id: 1>
856
- </ruby>
857
-
858
- h3. Running Callbacks
859
-
860
- The following methods trigger callbacks:
861
-
862
- * +create+
863
- * +create!+
864
- * +decrement!+
865
- * +destroy+
866
- * +destroy_all+
867
- * +increment!+
868
- * +save+
869
- * +save!+
870
- * +save(false)+
871
- * +toggle!+
872
- * +update+
873
- * +update_attribute+
874
- * +update_attributes+
875
- * +update_attributes!+
876
- * +valid?+
877
-
878
- Additionally, the +after_find+ callback is triggered by the following finder methods:
879
-
880
- * +all+
881
- * +first+
882
- * +find+
883
- * +find_all_by_<em>attribute</em>+
884
- * +find_by_<em>attribute</em>+
885
- * +find_by_<em>attribute</em>!+
886
- * +last+
887
-
888
- The +after_initialize+ callback is triggered every time a new object of the class is initialized.
889
-
890
- h3. Skipping Callbacks
891
-
892
- 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.
893
-
894
- * +decrement+
895
- * +decrement_counter+
896
- * +delete+
897
- * +delete_all+
898
- * +find_by_sql+
899
- * +increment+
900
- * +increment_counter+
901
- * +toggle+
902
- * +update_all+
903
- * +update_counters+
904
-
905
- h3. Halting Execution
906
-
907
- 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.
908
-
909
- The whole callback chain is wrapped in a transaction. If any before callback method returns exactly +false+ or raises an exception the execution chain gets halted and a ROLLBACK is issued. After callbacks can only accomplish that by raising an exception.
910
-
911
- 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.
912
-
913
- h3. Relational Callbacks
914
-
915
- 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.
916
-
917
- <ruby>
918
- class User < ActiveRecord::Base
919
- has_many :posts, :dependent => :destroy
920
- end
921
-
922
- class Post < ActiveRecord::Base
923
- after_destroy :log_destroy_action
924
-
925
- def log_destroy_action
926
- puts 'Post destroyed'
927
- end
928
- end
929
-
930
- >> user = User.first
931
- => #<User id: 1>
932
- >> user.posts.create!
933
- => #<Post id: 1, user_id: 1>
934
- >> user.destroy
935
- Post destroyed
936
- => #<User id: 1>
937
- </ruby>
938
-
939
- h3. Conditional Callbacks
940
-
941
- 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.
942
-
943
- h4. Using +:if+ and +:unless+ with a Symbol
944
-
945
- You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before the callback. If this method returns +false+ the callback won't be executed. This is the most common option. Using this form of registration it's also possible to register several different methods that should be called to check if the callback should be executed.
946
-
947
- <ruby>
948
- class Order < ActiveRecord::Base
949
- before_save :normalize_card_number, :if => :paid_with_card?
950
- end
951
- </ruby>
952
-
953
- h4. Using +:if+ and +:unless+ with a String
954
-
955
- 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.
956
-
957
- <ruby>
958
- class Order < ActiveRecord::Base
959
- before_save :normalize_card_number, :if => "paid_with_card?"
960
- end
961
- </ruby>
962
-
963
- h4. Using +:if+ and +:unless+ with a Proc
964
-
965
- 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.
966
-
967
- <ruby>
968
- class Order < ActiveRecord::Base
969
- before_save :normalize_card_number,
970
- :if => Proc.new { |order| order.paid_with_card? }
971
- end
972
- </ruby>
973
-
974
- h4. Multiple Conditions for Callbacks
975
-
976
- When writing conditional callbacks, it's possible to mix both +:if+ and +:unless+ in the same callback declaration.
977
-
978
- <ruby>
979
- class Comment < ActiveRecord::Base
980
- after_create :send_email_to_author, :if => :author_wants_emails?,
981
- :unless => Proc.new { |comment| comment.post.ignore_comments? }
982
- end
983
- </ruby>
984
-
985
- h3. Callback Classes
986
-
987
- 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.
988
-
989
- Here's an example where we create a class with an +after_destroy+ callback for a +PictureFile+ model.
990
-
991
- <ruby>
992
- class PictureFileCallbacks
993
- def after_destroy(picture_file)
994
- File.delete(picture_file.filepath)
995
- if File.exists?(picture_file.filepath)
996
- end
997
- end
998
- </ruby>
999
-
1000
- When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way:
1001
-
1002
- <ruby>
1003
- class PictureFile < ActiveRecord::Base
1004
- after_destroy PictureFileCallbacks.new
1005
- end
1006
- </ruby>
1007
-
1008
- 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.
1009
-
1010
- <ruby>
1011
- class PictureFileCallbacks
1012
- def self.after_destroy(picture_file)
1013
- File.delete(picture_file.filepath)
1014
- if File.exists?(picture_file.filepath)
1015
- end
1016
- end
1017
- </ruby>
1018
-
1019
- If the callback method is declared this way, it won't be necessary to instantiate a +PictureFileCallbacks+ object.
1020
-
1021
- <ruby>
1022
- class PictureFile < ActiveRecord::Base
1023
- after_destroy PictureFileCallbacks
1024
- end
1025
- </ruby>
1026
-
1027
- You can declare as many callbacks as you want inside your callback classes.
1028
-
1029
- h3. Observers
1030
-
1031
- 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.
1032
-
1033
- h4. Creating Observers
1034
-
1035
- 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.
1036
-
1037
- <ruby>
1038
- class UserObserver < ActiveRecord::Observer
1039
- def after_create(model)
1040
- # code to send confirmation email...
1041
- end
1042
- end
1043
- </ruby>
1044
-
1045
- As with callback classes, the observer's methods receive the observed model as a parameter.
1046
-
1047
- h4. Registering Observers
1048
-
1049
- Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/environment.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/environment.rb+ this way:
1050
-
1051
- <ruby>
1052
- # Activate observers that should always be running
1053
- config.active_record.observers = :user_observer
1054
- </ruby>
1055
-
1056
- As usual, settings in +config/environments+ take precedence over those in +config/environment.rb+. So, if you prefer that an observer not run in all environments, you can simply register it in a specific environment instead.
1057
-
1058
- h4. Sharing Observers
1059
-
1060
- 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.
1061
-
1062
- <ruby>
1063
- class MailerObserver < ActiveRecord::Observer
1064
- observe :registration, :user
1065
-
1066
- def after_create(model)
1067
- # code to send confirmation email...
1068
- end
1069
- end
1070
- </ruby>
1071
-
1072
- In this example, the +after_create+ method would be called whenever a +Registration+ or +User+ was created. Note that this new +MailerObserver+ would also need to be registered in +config/environment.rb+ in order to take effect.
1073
-
1074
- <ruby>
1075
- # Activate observers that should always be running
1076
- config.active_record.observers = :mailer_observer
1077
- </ruby>
1078
-
1079
- h3. Changelog
1080
-
1081
- "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks
1082
-
1083
- * March 7, 2009: Callbacks revision by Trevor Turk
1084
- * February 10, 2009: Observers revision by Trevor Turk
1085
- * February 5, 2009: Initial revision by Trevor Turk
1086
- * January 9, 2009: Initial version by "Cássio Marques":credits.html#cmarques