-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactive_record_callbacks.html
615 lines (558 loc) · 32.4 KB
/
active_record_callbacks.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Active Record Callbacks — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" data-turbolinks-track="reload">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="javascripts/syntaxhighlighter.js" data-turbolinks-track="reload"></script>
<script src="javascripts/turbolinks.js" data-turbolinks-track="reload"></script>
<script src="javascripts/guides.js" data-turbolinks-track="reload"></script>
<script src="javascripts/responsive-tables.js" data-turbolinks-track="reload"></script>
</head>
<body class="guide">
<div>
<img src="images/edge_badge.png" alt="edge-badge" id="edge-badge" />
</div>
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">Veja mais em <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
Mais Ruby on Rails
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">Blog</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">Guia</a></li>
<li class="more-info"><a href="http://api.rubyonrails.org/">API</a></li>
<li class="more-info"><a href="https://stackoverflow.com/questions/tagged/ruby-on-rails">Pedir ajuda</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">Contribuir no GitHub</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">Home</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Guias</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<div class="guides-section-container">
<div class="guides-section">
<dt>Comece Aqui</dt>
</div>
<div class="guides-section">
<dt>Models</dt>
</div>
<div class="guides-section">
<dt>Views</dt>
</div>
<div class="guides-section">
<dt>Controllers</dt>
</div>
<div class="guides-section">
<dt>Other Components</dt>
</div>
<div class="guides-section">
<dt>Digging Deeper</dt>
</div>
<div class="guides-section">
<dt>Extending Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd>
</div>
<div class="guides-section">
<dt>Contributions</dt>
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd>
</div>
<div class="guides-section">
<dt>Policies</dt>
<dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
</div>
<div class="guides-section">
<dt>Release Notes</dt>
<dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
<dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd>
<dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd>
<dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd>
<dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd>
<dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd>
<dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd>
<dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd>
<dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd>
<dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd>
<dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd>
<dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd>
</div>
</div>
</div>
</li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribua</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">Guias</option>
<optgroup label="Comece Aqui">
</optgroup>
<optgroup label="Models">
</optgroup>
<optgroup label="Views">
</optgroup>
<optgroup label="Controllers">
</optgroup>
<optgroup label="Other Components">
</optgroup>
<optgroup label="Digging Deeper">
</optgroup>
<optgroup label="Extending Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">Creating and Customizing Rails Generators & Templates</option>
</optgroup>
<optgroup label="Contributions">
<option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
<option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option>
</optgroup>
<optgroup label="Policies">
<option value="maintenance_policy.html">Maintenance Policy</option>
</optgroup>
<optgroup label="Release Notes">
<option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
<option value="5_2_release_notes.html">Version 5.2 - April 2018</option>
<option value="5_1_release_notes.html">Version 5.1 - April 2017</option>
<option value="5_0_release_notes.html">Version 5.0 - June 2016</option>
<option value="4_2_release_notes.html">Version 4.2 - December 2014</option>
<option value="4_1_release_notes.html">Version 4.1 - April 2014</option>
<option value="4_0_release_notes.html">Version 4.0 - June 2013</option>
<option value="3_2_release_notes.html">Version 3.2 - January 2012</option>
<option value="3_1_release_notes.html">Version 3.1 - August 2011</option>
<option value="3_0_release_notes.html">Version 3.0 - August 2010</option>
<option value="2_3_release_notes.html">Version 2.3 - March 2009</option>
<option value="2_2_release_notes.html">Version 2.2 - November 2008</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Active Record Callbacks</h2><p>This guide teaches you how to hook into the life cycle of your Active Record
objects.</p><p>After reading this guide, you will know:</p>
<ul>
<li>The life cycle of Active Record objects.</li>
<li>How to create callback methods that respond to events in the object life cycle.</li>
<li>How to create special classes that encapsulate common behavior for your callbacks.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#the-object-life-cycle">The Object Life Cycle</a></li>
<li>
<a href="#callbacks-overview">Callbacks Overview</a>
<ul>
<li><a href="#callback-registration">Callback Registration</a></li>
</ul>
</li>
<li>
<a href="#available-callbacks">Available Callbacks</a>
<ul>
<li><a href="#creating-an-object">Creating an Object</a></li>
<li><a href="#updating-an-object">Updating an Object</a></li>
<li><a href="#destroying-an-object">Destroying an Object</a></li>
<li><a href="#after-initialize-and-after-find"><code>after_initialize</code> and <code>after_find</code></a></li>
<li><a href="#after-touch"><code>after_touch</code></a></li>
</ul>
</li>
<li><a href="#running-callbacks">Running Callbacks</a></li>
<li><a href="#skipping-callbacks">Skipping Callbacks</a></li>
<li><a href="#halting-execution">Halting Execution</a></li>
<li><a href="#relational-callbacks">Relational Callbacks</a></li>
<li>
<a href="#conditional-callbacks">Conditional Callbacks</a>
<ul>
<li><a href="#using-if-and-unless-with-a-symbol">Using <code>:if</code> and <code>:unless</code> with a <code>Symbol</code></a></li>
<li><a href="#using-if-and-unless-with-a-proc">Using <code>:if</code> and <code>:unless</code> with a <code>Proc</code></a></li>
<li><a href="#multiple-conditions-for-callbacks">Multiple Conditions for Callbacks</a></li>
</ul>
</li>
<li><a href="#callback-classes">Callback Classes</a></li>
<li><a href="#transaction-callbacks">Transaction Callbacks</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="the-object-life-cycle"><a class="anchorlink" href="#the-object-life-cycle">1 The Object Life Cycle</a></h3><p>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.</p><p>Callbacks allow you to trigger logic before or after an alteration of an object's state.</p><h3 id="callbacks-overview"><a class="anchorlink" href="#callbacks-overview">2 Callbacks Overview</a></h3><p>Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.</p><h4 id="callback-registration"><a class="anchorlink" href="#callback-registration">2.1 Callback Registration</a></h4><p>In order to use the available callbacks, you need to register them. You can implement the callbacks as ordinary methods and use a macro-style class method to register them as callbacks:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
validates :login, :email, presence: true
before_validation :ensure_login_has_a_value
private
def ensure_login_has_a_value
if login.nil?
self.login = email unless email.blank?
end
end
end
</pre>
</div>
<p>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 a single line:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
validates :login, :email, presence: true
before_create do
self.name = login.capitalize if name.blank?
end
end
</pre>
</div>
<p>Callbacks can also be registered to only fire on certain life cycle events:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
before_validation :normalize_name, on: :create
# :on takes an array as well
after_validation :set_location, on: [ :create, :update ]
private
def normalize_name
self.name = name.downcase.titleize
end
def set_location
self.location = LocationService.query(self)
end
end
</pre>
</div>
<p>It is considered good practice to declare callback methods as private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.</p><h3 id="available-callbacks"><a class="anchorlink" href="#available-callbacks">3 Available Callbacks</a></h3><p>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:</p><h4 id="creating-an-object"><a class="anchorlink" href="#creating-an-object">3.1 Creating an Object</a></h4>
<ul>
<li><code>before_validation</code></li>
<li><code>after_validation</code></li>
<li><code>before_save</code></li>
<li><code>around_save</code></li>
<li><code>before_create</code></li>
<li><code>around_create</code></li>
<li><code>after_create</code></li>
<li><code>after_save</code></li>
<li><code>after_commit/after_rollback</code></li>
</ul>
<h4 id="updating-an-object"><a class="anchorlink" href="#updating-an-object">3.2 Updating an Object</a></h4>
<ul>
<li><code>before_validation</code></li>
<li><code>after_validation</code></li>
<li><code>before_save</code></li>
<li><code>around_save</code></li>
<li><code>before_update</code></li>
<li><code>around_update</code></li>
<li><code>after_update</code></li>
<li><code>after_save</code></li>
<li><code>after_commit/after_rollback</code></li>
</ul>
<h4 id="destroying-an-object"><a class="anchorlink" href="#destroying-an-object">3.3 Destroying an Object</a></h4>
<ul>
<li><code>before_destroy</code></li>
<li><code>around_destroy</code></li>
<li><code>after_destroy</code></li>
<li><code>after_commit/after_rollback</code></li>
</ul>
<div class="warning"><p><code>after_save</code> runs both on create and update, but always <em>after</em> the more specific callbacks <code>after_create</code> and <code>after_update</code>, no matter the order in which the macro calls were executed.</p></div><div class="note"><p><code>before_destroy</code> callbacks should be placed before <code>dependent: :destroy</code>
associations (or use the <code>prepend: true</code> option), to ensure they execute before
the records are deleted by <code>dependent: :destroy</code>.</p></div><h4 id="after-initialize-and-after-find"><a class="anchorlink" href="#after-initialize-and-after-find">3.4 <code>after_initialize</code> and <code>after_find</code></a></h4><p>The <code>after_initialize</code> callback will be called whenever an Active Record object is instantiated, either by directly using <code>new</code> or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record <code>initialize</code> method.</p><p>The <code>after_find</code> callback will be called whenever Active Record loads a record from the database. <code>after_find</code> is called before <code>after_initialize</code> if both are defined.</p><p>The <code>after_initialize</code> and <code>after_find</code> callbacks have no <code>before_*</code> counterparts, but they can be registered just like the other Active Record callbacks.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
after_initialize do |user|
puts "You have initialized an object!"
end
after_find do |user|
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>
</pre>
</div>
<h4 id="after-touch"><a class="anchorlink" href="#after-touch">3.5 <code>after_touch</code></a></h4><p>The <code>after_touch</code> callback will be called whenever an Active Record object is touched.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
after_touch do |user|
puts "You have touched an object"
end
end
>> u = User.create(name: 'Kuldeep')
=> #<User id: 1, name: "Kuldeep", created_at: "2013-11-25 12:17:49", updated_at: "2013-11-25 12:17:49">
>> u.touch
You have touched an object
=> true
</pre>
</div>
<p>It can be used along with <code>belongs_to</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Employee < ApplicationRecord
belongs_to :company, touch: true
after_touch do
puts 'An Employee was touched'
end
end
class Company < ApplicationRecord
has_many :employees
after_touch :log_when_employees_or_company_touched
private
def log_when_employees_or_company_touched
puts 'Employee/Company was touched'
end
end
>> @employee = Employee.last
=> #<Employee id: 1, company_id: 1, created_at: "2013-11-25 17:04:22", updated_at: "2013-11-25 17:05:05">
# triggers @employee.company.touch
>> @employee.touch
An Employee was touched
Employee/Company was touched
=> true
</pre>
</div>
<h3 id="running-callbacks"><a class="anchorlink" href="#running-callbacks">4 Running Callbacks</a></h3><p>The following methods trigger callbacks:</p>
<ul>
<li><code>create</code></li>
<li><code>create!</code></li>
<li><code>destroy</code></li>
<li><code>destroy!</code></li>
<li><code>destroy_all</code></li>
<li><code>save</code></li>
<li><code>save!</code></li>
<li><code>save(validate: false)</code></li>
<li><code>toggle!</code></li>
<li><code>touch</code></li>
<li><code>update_attribute</code></li>
<li><code>update</code></li>
<li><code>update!</code></li>
<li><code>valid?</code></li>
</ul>
<p>Additionally, the <code>after_find</code> callback is triggered by the following finder methods:</p>
<ul>
<li><code>all</code></li>
<li><code>first</code></li>
<li><code>find</code></li>
<li><code>find_by</code></li>
<li><code>find_by_*</code></li>
<li><code>find_by_*!</code></li>
<li><code>find_by_sql</code></li>
<li><code>last</code></li>
</ul>
<p>The <code>after_initialize</code> callback is triggered every time a new object of the class is initialized.</p><div class="note"><p>The <code>find_by_*</code> and <code>find_by_*!</code> methods are dynamic finders generated automatically for every attribute. Learn more about them at the <a href="active_record_querying.html#dynamic-finders">Dynamic finders section</a></p></div><h3 id="skipping-callbacks"><a class="anchorlink" href="#skipping-callbacks">5 Skipping Callbacks</a></h3><p>Just as with validations, it is also possible to skip callbacks by using the following methods:</p>
<ul>
<li><code>decrement</code></li>
<li><code>decrement_counter</code></li>
<li><code>delete</code></li>
<li><code>delete_all</code></li>
<li><code>increment</code></li>
<li><code>increment_counter</code></li>
<li><code>toggle</code></li>
<li><code>update_column</code></li>
<li><code>update_columns</code></li>
<li><code>update_all</code></li>
<li><code>update_counters</code></li>
</ul>
<p>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><h3 id="halting-execution"><a class="anchorlink" href="#halting-execution">6 Halting Execution</a></h3><p>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><p>The whole callback chain is wrapped in a transaction. If any callback raises an exception, the execution chain gets halted and a ROLLBACK is issued. To intentionally stop a chain use:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
throw :abort
</pre>
</div>
<div class="warning"><p>Any exception that is not <code>ActiveRecord::Rollback</code> or <code>ActiveRecord::RecordInvalid</code> will be re-raised by Rails after the callback chain is halted. Raising an exception other than <code>ActiveRecord::Rollback</code> or <code>ActiveRecord::RecordInvalid</code> may break code that does not expect methods like <code>save</code> and <code>update</code> (which normally try to return <code>true</code> or <code>false</code>) to raise an exception.</p></div><h3 id="relational-callbacks"><a class="anchorlink" href="#relational-callbacks">7 Relational Callbacks</a></h3><p>Callbacks work through model relationships, and can even be defined by them. Suppose an example where a user has many articles. A user's articles should be destroyed if the user is destroyed. Let's add an <code>after_destroy</code> callback to the <code>User</code> model by way of its relationship to the <code>Article</code> model:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
has_many :articles, dependent: :destroy
end
class Article < ApplicationRecord
after_destroy :log_destroy_action
def log_destroy_action
puts 'Article destroyed'
end
end
>> user = User.first
=> #<User id: 1>
>> user.articles.create!
=> #<Article id: 1, user_id: 1>
>> user.destroy
Article destroyed
=> #<User id: 1>
</pre>
</div>
<h3 id="conditional-callbacks"><a class="anchorlink" href="#conditional-callbacks">8 Conditional Callbacks</a></h3><p>As with validations, we can also make the calling of a callback method conditional on the satisfaction of a given predicate. We can do this using the <code>:if</code> and <code>:unless</code> options, which can take a symbol, a <code>Proc</code> or an <code>Array</code>. You may use the <code>:if</code> option when you want to specify under which conditions the callback <strong>should</strong> be called. If you want to specify the conditions under which the callback <strong>should not</strong> be called, then you may use the <code>:unless</code> option.</p><h4 id="using-if-and-unless-with-a-symbol"><a class="anchorlink" href="#using-if-and-unless-with-a-symbol">8.1 Using <code>:if</code> and <code>:unless</code> with a <code>Symbol</code></a></h4><p>You can associate the <code>:if</code> and <code>:unless</code> options with a symbol corresponding to the name of a predicate method that will get called right before the callback. When using the <code>:if</code> option, the callback won't be executed if the predicate method returns false; when using the <code>:unless</code> option, the callback won't be executed if the predicate method returns true. This is the most common option. Using this form of registration it is also possible to register several different predicates that should be called to check if the callback should be executed.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Order < ApplicationRecord
before_save :normalize_card_number, if: :paid_with_card?
end
</pre>
</div>
<h4 id="using-if-and-unless-with-a-proc"><a class="anchorlink" href="#using-if-and-unless-with-a-proc">8.2 Using <code>:if</code> and <code>:unless</code> with a <code>Proc</code></a></h4><p>Finally, it is possible to associate <code>:if</code> and <code>:unless</code> with a <code>Proc</code> object. This option is best suited when writing short validation methods, usually one-liners:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Order < ApplicationRecord
before_save :normalize_card_number,
if: Proc.new { |order| order.paid_with_card? }
end
</pre>
</div>
<p>As the proc is evaluated in the context of the object, it is also possible to write this as:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Order < ApplicationRecord
before_save :normalize_card_number, if: Proc.new { paid_with_card? }
end
</pre>
</div>
<h4 id="multiple-conditions-for-callbacks"><a class="anchorlink" href="#multiple-conditions-for-callbacks">8.3 Multiple Conditions for Callbacks</a></h4><p>When writing conditional callbacks, it is possible to mix both <code>:if</code> and <code>:unless</code> in the same callback declaration:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Comment < ApplicationRecord
after_create :send_email_to_author, if: :author_wants_emails?,
unless: Proc.new { |comment| comment.article.ignore_comments? }
end
</pre>
</div>
<h3 id="callback-classes"><a class="anchorlink" href="#callback-classes">9 Callback Classes</a></h3><p>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.</p><p>Here's an example where we create a class with an <code>after_destroy</code> callback for a <code>PictureFile</code> model:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class PictureFileCallbacks
def after_destroy(picture_file)
if File.exist?(picture_file.filepath)
File.delete(picture_file.filepath)
end
end
end
</pre>
</div>
<p>When declared inside a class, as above, the callback methods will receive the model object as a parameter. We can now use the callback class in the model:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class PictureFile < ApplicationRecord
after_destroy PictureFileCallbacks.new
end
</pre>
</div>
<p>Note that we needed to instantiate a new <code>PictureFileCallbacks</code> object, since we declared our callback as an instance method. This is particularly useful if the callbacks make use of the state of the instantiated object. Often, however, it will make more sense to declare the callbacks as class methods:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class PictureFileCallbacks
def self.after_destroy(picture_file)
if File.exist?(picture_file.filepath)
File.delete(picture_file.filepath)
end
end
end
</pre>
</div>
<p>If the callback method is declared this way, it won't be necessary to instantiate a <code>PictureFileCallbacks</code> object.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class PictureFile < ApplicationRecord
after_destroy PictureFileCallbacks
end
</pre>
</div>
<p>You can declare as many callbacks as you want inside your callback classes.</p><h3 id="transaction-callbacks"><a class="anchorlink" href="#transaction-callbacks">10 Transaction Callbacks</a></h3><p>There are two additional callbacks that are triggered by the completion of a database transaction: <code>after_commit</code> and <code>after_rollback</code>. These callbacks are very similar to the <code>after_save</code> callback except that they don't execute until after database changes have either been committed or rolled back. They are most useful when your active record models need to interact with external systems which are not part of the database transaction.</p><p>Consider, for example, the previous example where the <code>PictureFile</code> model needs to delete a file after the corresponding record is destroyed. If anything raises an exception after the <code>after_destroy</code> callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that <code>picture_file_2</code> in the code below is not valid and the <code>save!</code> method raises an error.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
PictureFile.transaction do
picture_file_1.destroy
picture_file_2.save!
end
</pre>
</div>
<p>By using the <code>after_commit</code> callback we can account for this case.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class PictureFile < ApplicationRecord
after_commit :delete_picture_file_from_disk, on: :destroy
def delete_picture_file_from_disk
if File.exist?(filepath)
File.delete(filepath)
end
end
end
</pre>
</div>
<div class="note"><p>The <code>:on</code> option specifies when a callback will be fired. If you
don't supply the <code>:on</code> option the callback will fire for every action.</p></div><p>Since using <code>after_commit</code> callback only on create, update, or delete is
common, there are aliases for those operations:</p>
<ul>
<li><code>after_create_commit</code></li>
<li><code>after_update_commit</code></li>
<li><code>after_destroy_commit</code></li>
</ul>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class PictureFile < ApplicationRecord
after_destroy_commit :delete_picture_file_from_disk
def delete_picture_file_from_disk
if File.exist?(filepath)
File.delete(filepath)
end
end
end
</pre>
</div>
<div class="warning"><p>When a transaction completes, the <code>after_commit</code> or <code>after_rollback</code> callbacks are called for all models created, updated, or destroyed within that transaction. However, if an exception is raised within one of these callbacks, the exception will bubble up and any remaining <code>after_commit</code> or <code>after_rollback</code> methods will <em>not</em> be executed. As such, if your callback code could raise an exception, you'll need to rescue it and handle it within the callback in order to allow other callbacks to run.</p></div><div class="warning"><p>The code executed within <code>after_commit</code> or <code>after_rollback</code> callbacks is itself not enclosed within a transaction.</p></div><div class="warning"><p>Using both <code>after_create_commit</code> and <code>after_update_commit</code> in the same model will only allow the last callback defined to take effect, and will override all others.</p></div><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
after_create_commit :log_user_saved_to_db
after_update_commit :log_user_saved_to_db
private
def log_user_saved_to_db
puts 'User was saved to database'
end
end
# prints nothing
>> @user = User.create
# updating @user
>> @user.save
=> User was saved to database
</pre>
</div>
<p>To register callbacks for both create and update actions, use <code>after_commit</code> instead.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
after_commit :log_user_saved_to_db, on: [:create, :update]
end
</pre>
</div>
<h3>Feedback</h3>
<p>
You're encouraged to help improve the quality of this guide.
</p>
<p>
Please contribute if you see any typos or factual errors.
To get started, you can read our <a href="https://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">documentation contributions</a> section.
</p>
<p>
You may also find incomplete content or stuff that is not up to date.
Please do add any missing documentation for master. Make sure to check
<a href="https://edgeguides.rubyonrails.org">Edge Guides</a> first to verify
if the issues are already fixed or not on the master branch.
Check the <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
for style and conventions.
</p>
<p>
If for whatever reason you spot something to fix but cannot patch it yourself, please
<a href="https://github.com/rails/rails/issues">open an issue</a>.
</p>
<p>And last but not least, any kind of discussion regarding Ruby on Rails
documentation is very welcome on the <a href="https://groups.google.com/forum/#!forum/rubyonrails-docs">rubyonrails-docs mailing list</a>.
</p>
</div>
</div>
</div>
<hr class="hide" />
<div id="footer">
<div class="wrapper">
<p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p>
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
</div>
</div>
</body>
</html>