rails 4.2.6.rc1 → 5.2.8.1
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.
- checksums.yaml +5 -5
- data/README.md +24 -12
- metadata +54 -248
- data/guides/CHANGELOG.md +0 -73
- data/guides/Rakefile +0 -79
- data/guides/assets/images/akshaysurve.jpg +0 -0
- data/guides/assets/images/belongs_to.png +0 -0
- data/guides/assets/images/book_icon.gif +0 -0
- data/guides/assets/images/bullet.gif +0 -0
- data/guides/assets/images/chapters_icon.gif +0 -0
- data/guides/assets/images/check_bullet.gif +0 -0
- data/guides/assets/images/credits_pic_blank.gif +0 -0
- data/guides/assets/images/csrf.png +0 -0
- data/guides/assets/images/edge_badge.png +0 -0
- data/guides/assets/images/favicon.ico +0 -0
- data/guides/assets/images/feature_tile.gif +0 -0
- data/guides/assets/images/footer_tile.gif +0 -0
- data/guides/assets/images/fxn.png +0 -0
- data/guides/assets/images/getting_started/article_with_comments.png +0 -0
- data/guides/assets/images/getting_started/challenge.png +0 -0
- data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
- data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
- data/guides/assets/images/getting_started/form_with_errors.png +0 -0
- data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
- data/guides/assets/images/getting_started/new_article.png +0 -0
- data/guides/assets/images/getting_started/rails_welcome.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
- data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
- data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
- data/guides/assets/images/grey_bullet.gif +0 -0
- data/guides/assets/images/habtm.png +0 -0
- data/guides/assets/images/has_many.png +0 -0
- data/guides/assets/images/has_many_through.png +0 -0
- data/guides/assets/images/has_one.png +0 -0
- data/guides/assets/images/has_one_through.png +0 -0
- data/guides/assets/images/header_backdrop.png +0 -0
- data/guides/assets/images/header_tile.gif +0 -0
- data/guides/assets/images/i18n/demo_html_safe.png +0 -0
- data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translated_en.png +0 -0
- data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
- data/guides/assets/images/i18n/demo_untranslated.png +0 -0
- data/guides/assets/images/icons/README +0 -5
- data/guides/assets/images/icons/callouts/1.png +0 -0
- data/guides/assets/images/icons/callouts/10.png +0 -0
- data/guides/assets/images/icons/callouts/11.png +0 -0
- data/guides/assets/images/icons/callouts/12.png +0 -0
- data/guides/assets/images/icons/callouts/13.png +0 -0
- data/guides/assets/images/icons/callouts/14.png +0 -0
- data/guides/assets/images/icons/callouts/15.png +0 -0
- data/guides/assets/images/icons/callouts/2.png +0 -0
- data/guides/assets/images/icons/callouts/3.png +0 -0
- data/guides/assets/images/icons/callouts/4.png +0 -0
- data/guides/assets/images/icons/callouts/5.png +0 -0
- data/guides/assets/images/icons/callouts/6.png +0 -0
- data/guides/assets/images/icons/callouts/7.png +0 -0
- data/guides/assets/images/icons/callouts/8.png +0 -0
- data/guides/assets/images/icons/callouts/9.png +0 -0
- data/guides/assets/images/icons/caution.png +0 -0
- data/guides/assets/images/icons/example.png +0 -0
- data/guides/assets/images/icons/home.png +0 -0
- data/guides/assets/images/icons/important.png +0 -0
- data/guides/assets/images/icons/next.png +0 -0
- data/guides/assets/images/icons/note.png +0 -0
- data/guides/assets/images/icons/prev.png +0 -0
- data/guides/assets/images/icons/tip.png +0 -0
- data/guides/assets/images/icons/up.png +0 -0
- data/guides/assets/images/icons/warning.png +0 -0
- data/guides/assets/images/nav_arrow.gif +0 -0
- data/guides/assets/images/oscardelben.jpg +0 -0
- data/guides/assets/images/polymorphic.png +0 -0
- data/guides/assets/images/radar.png +0 -0
- data/guides/assets/images/rails4_features.png +0 -0
- data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
- data/guides/assets/images/rails_guides_logo.gif +0 -0
- data/guides/assets/images/rails_logo_remix.gif +0 -0
- data/guides/assets/images/session_fixation.png +0 -0
- data/guides/assets/images/tab_grey.gif +0 -0
- data/guides/assets/images/tab_info.gif +0 -0
- data/guides/assets/images/tab_note.gif +0 -0
- data/guides/assets/images/tab_red.gif +0 -0
- data/guides/assets/images/tab_yellow.gif +0 -0
- data/guides/assets/images/tab_yellow.png +0 -0
- data/guides/assets/images/vijaydev.jpg +0 -0
- data/guides/assets/javascripts/guides.js +0 -59
- data/guides/assets/javascripts/jquery.min.js +0 -4
- data/guides/assets/javascripts/responsive-tables.js +0 -43
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
- data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
- data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
- data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
- data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
- data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
- data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
- data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
- data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
- data/guides/assets/stylesheets/fixes.css +0 -16
- data/guides/assets/stylesheets/kindle.css +0 -11
- data/guides/assets/stylesheets/main.css +0 -713
- data/guides/assets/stylesheets/print.css +0 -52
- data/guides/assets/stylesheets/reset.css +0 -43
- data/guides/assets/stylesheets/responsive-tables.css +0 -50
- data/guides/assets/stylesheets/style.css +0 -13
- data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
- data/guides/bug_report_templates/action_controller_gem.rb +0 -47
- data/guides/bug_report_templates/action_controller_master.rb +0 -54
- data/guides/bug_report_templates/active_record_gem.rb +0 -40
- data/guides/bug_report_templates/active_record_master.rb +0 -49
- data/guides/bug_report_templates/generic_gem.rb +0 -15
- data/guides/bug_report_templates/generic_master.rb +0 -26
- data/guides/rails_guides/generator.rb +0 -248
- data/guides/rails_guides/helpers.rb +0 -53
- data/guides/rails_guides/indexer.rb +0 -68
- data/guides/rails_guides/kindle.rb +0 -119
- data/guides/rails_guides/levenshtein.rb +0 -37
- data/guides/rails_guides/markdown/renderer.rb +0 -82
- data/guides/rails_guides/markdown.rb +0 -167
- data/guides/rails_guides.rb +0 -63
- data/guides/source/2_2_release_notes.md +0 -435
- data/guides/source/2_3_release_notes.md +0 -621
- data/guides/source/3_0_release_notes.md +0 -611
- data/guides/source/3_1_release_notes.md +0 -559
- data/guides/source/3_2_release_notes.md +0 -568
- data/guides/source/4_0_release_notes.md +0 -279
- data/guides/source/4_1_release_notes.md +0 -730
- data/guides/source/4_2_release_notes.md +0 -877
- data/guides/source/_license.html.erb +0 -2
- data/guides/source/_welcome.html.erb +0 -23
- data/guides/source/action_controller_overview.md +0 -1192
- data/guides/source/action_mailer_basics.md +0 -757
- data/guides/source/action_view_overview.md +0 -1561
- data/guides/source/active_job_basics.md +0 -339
- data/guides/source/active_model_basics.md +0 -554
- data/guides/source/active_record_basics.md +0 -374
- data/guides/source/active_record_callbacks.md +0 -413
- data/guides/source/active_record_migrations.md +0 -1018
- data/guides/source/active_record_postgresql.md +0 -433
- data/guides/source/active_record_querying.md +0 -1781
- data/guides/source/active_record_validations.md +0 -1179
- data/guides/source/active_support_core_extensions.md +0 -3857
- data/guides/source/active_support_instrumentation.md +0 -488
- data/guides/source/api_documentation_guidelines.md +0 -361
- data/guides/source/asset_pipeline.md +0 -1304
- data/guides/source/association_basics.md +0 -2245
- data/guides/source/autoloading_and_reloading_constants.md +0 -1311
- data/guides/source/caching_with_rails.md +0 -379
- data/guides/source/command_line.md +0 -625
- data/guides/source/configuring.md +0 -1072
- data/guides/source/contributing_to_ruby_on_rails.md +0 -628
- data/guides/source/credits.html.erb +0 -80
- data/guides/source/debugging_rails_applications.md +0 -861
- data/guides/source/development_dependencies_install.md +0 -289
- data/guides/source/documents.yaml +0 -205
- data/guides/source/engines.md +0 -1412
- data/guides/source/form_helpers.md +0 -1024
- data/guides/source/generators.md +0 -676
- data/guides/source/getting_started.md +0 -2086
- data/guides/source/i18n.md +0 -1087
- data/guides/source/index.html.erb +0 -28
- data/guides/source/initialization.md +0 -704
- data/guides/source/kindle/copyright.html.erb +0 -1
- data/guides/source/kindle/layout.html.erb +0 -27
- data/guides/source/kindle/rails_guides.opf.erb +0 -52
- data/guides/source/kindle/toc.html.erb +0 -24
- data/guides/source/kindle/toc.ncx.erb +0 -64
- data/guides/source/kindle/welcome.html.erb +0 -5
- data/guides/source/layout.html.erb +0 -140
- data/guides/source/layouts_and_rendering.md +0 -1227
- data/guides/source/maintenance_policy.md +0 -78
- data/guides/source/nested_model_forms.md +0 -228
- data/guides/source/plugins.md +0 -444
- data/guides/source/rails_application_templates.md +0 -266
- data/guides/source/rails_on_rack.md +0 -336
- data/guides/source/routing.md +0 -1155
- data/guides/source/ruby_on_rails_guides_guidelines.md +0 -127
- data/guides/source/security.md +0 -1024
- data/guides/source/testing.md +0 -1132
- data/guides/source/upgrading_ruby_on_rails.md +0 -1186
- data/guides/source/working_with_javascript_in_rails.md +0 -407
- data/guides/w3c_validator.rb +0 -97
@@ -1,413 +0,0 @@
|
|
1
|
-
Active Record Callbacks
|
2
|
-
=======================
|
3
|
-
|
4
|
-
This guide teaches you how to hook into the life cycle of your Active Record
|
5
|
-
objects.
|
6
|
-
|
7
|
-
After reading this guide, you will know:
|
8
|
-
|
9
|
-
* The life cycle of Active Record objects.
|
10
|
-
* How to create callback methods that respond to events in the object life cycle.
|
11
|
-
* How to create special classes that encapsulate common behavior for your callbacks.
|
12
|
-
|
13
|
-
--------------------------------------------------------------------------------
|
14
|
-
|
15
|
-
The Object Life Cycle
|
16
|
-
---------------------
|
17
|
-
|
18
|
-
During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this *object life cycle* so that you can control your application and its data.
|
19
|
-
|
20
|
-
Callbacks allow you to trigger logic before or after an alteration of an object's state.
|
21
|
-
|
22
|
-
Callbacks Overview
|
23
|
-
------------------
|
24
|
-
|
25
|
-
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.
|
26
|
-
|
27
|
-
### Callback Registration
|
28
|
-
|
29
|
-
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:
|
30
|
-
|
31
|
-
```ruby
|
32
|
-
class User < ActiveRecord::Base
|
33
|
-
validates :login, :email, presence: true
|
34
|
-
|
35
|
-
before_validation :ensure_login_has_a_value
|
36
|
-
|
37
|
-
protected
|
38
|
-
def ensure_login_has_a_value
|
39
|
-
if login.nil?
|
40
|
-
self.login = email unless email.blank?
|
41
|
-
end
|
42
|
-
end
|
43
|
-
end
|
44
|
-
```
|
45
|
-
|
46
|
-
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:
|
47
|
-
|
48
|
-
```ruby
|
49
|
-
class User < ActiveRecord::Base
|
50
|
-
validates :login, :email, presence: true
|
51
|
-
|
52
|
-
before_create do
|
53
|
-
self.name = login.capitalize if name.blank?
|
54
|
-
end
|
55
|
-
end
|
56
|
-
```
|
57
|
-
|
58
|
-
Callbacks can also be registered to only fire on certain life cycle events:
|
59
|
-
|
60
|
-
```ruby
|
61
|
-
class User < ActiveRecord::Base
|
62
|
-
before_validation :normalize_name, on: :create
|
63
|
-
|
64
|
-
# :on takes an array as well
|
65
|
-
after_validation :set_location, on: [ :create, :update ]
|
66
|
-
|
67
|
-
protected
|
68
|
-
def normalize_name
|
69
|
-
self.name = self.name.downcase.titleize
|
70
|
-
end
|
71
|
-
|
72
|
-
def set_location
|
73
|
-
self.location = LocationService.query(self)
|
74
|
-
end
|
75
|
-
end
|
76
|
-
```
|
77
|
-
|
78
|
-
It is considered good practice to declare callback methods as protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.
|
79
|
-
|
80
|
-
Available Callbacks
|
81
|
-
-------------------
|
82
|
-
|
83
|
-
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:
|
84
|
-
|
85
|
-
### Creating an Object
|
86
|
-
|
87
|
-
* `before_validation`
|
88
|
-
* `after_validation`
|
89
|
-
* `before_save`
|
90
|
-
* `around_save`
|
91
|
-
* `before_create`
|
92
|
-
* `around_create`
|
93
|
-
* `after_create`
|
94
|
-
* `after_save`
|
95
|
-
* `after_commit/after_rollback`
|
96
|
-
|
97
|
-
### Updating an Object
|
98
|
-
|
99
|
-
* `before_validation`
|
100
|
-
* `after_validation`
|
101
|
-
* `before_save`
|
102
|
-
* `around_save`
|
103
|
-
* `before_update`
|
104
|
-
* `around_update`
|
105
|
-
* `after_update`
|
106
|
-
* `after_save`
|
107
|
-
* `after_commit/after_rollback`
|
108
|
-
|
109
|
-
### Destroying an Object
|
110
|
-
|
111
|
-
* `before_destroy`
|
112
|
-
* `around_destroy`
|
113
|
-
* `after_destroy`
|
114
|
-
* `after_commit/after_rollback`
|
115
|
-
|
116
|
-
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.
|
117
|
-
|
118
|
-
### `after_initialize` and `after_find`
|
119
|
-
|
120
|
-
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.
|
121
|
-
|
122
|
-
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.
|
123
|
-
|
124
|
-
The `after_initialize` and `after_find` callbacks have no `before_*` counterparts, but they can be registered just like the other Active Record callbacks.
|
125
|
-
|
126
|
-
```ruby
|
127
|
-
class User < ActiveRecord::Base
|
128
|
-
after_initialize do |user|
|
129
|
-
puts "You have initialized an object!"
|
130
|
-
end
|
131
|
-
|
132
|
-
after_find do |user|
|
133
|
-
puts "You have found an object!"
|
134
|
-
end
|
135
|
-
end
|
136
|
-
|
137
|
-
>> User.new
|
138
|
-
You have initialized an object!
|
139
|
-
=> #<User id: nil>
|
140
|
-
|
141
|
-
>> User.first
|
142
|
-
You have found an object!
|
143
|
-
You have initialized an object!
|
144
|
-
=> #<User id: 1>
|
145
|
-
```
|
146
|
-
|
147
|
-
### `after_touch`
|
148
|
-
|
149
|
-
The `after_touch` callback will be called whenever an Active Record object is touched.
|
150
|
-
|
151
|
-
```ruby
|
152
|
-
class User < ActiveRecord::Base
|
153
|
-
after_touch do |user|
|
154
|
-
puts "You have touched an object"
|
155
|
-
end
|
156
|
-
end
|
157
|
-
|
158
|
-
>> u = User.create(name: 'Kuldeep')
|
159
|
-
=> #<User id: 1, name: "Kuldeep", created_at: "2013-11-25 12:17:49", updated_at: "2013-11-25 12:17:49">
|
160
|
-
|
161
|
-
>> u.touch
|
162
|
-
You have touched an object
|
163
|
-
=> true
|
164
|
-
```
|
165
|
-
|
166
|
-
It can be used along with `belongs_to`:
|
167
|
-
|
168
|
-
```ruby
|
169
|
-
class Employee < ActiveRecord::Base
|
170
|
-
belongs_to :company, touch: true
|
171
|
-
after_touch do
|
172
|
-
puts 'An Employee was touched'
|
173
|
-
end
|
174
|
-
end
|
175
|
-
|
176
|
-
class Company < ActiveRecord::Base
|
177
|
-
has_many :employees
|
178
|
-
after_touch :log_when_employees_or_company_touched
|
179
|
-
|
180
|
-
private
|
181
|
-
def log_when_employees_or_company_touched
|
182
|
-
puts 'Employee/Company was touched'
|
183
|
-
end
|
184
|
-
end
|
185
|
-
|
186
|
-
>> @employee = Employee.last
|
187
|
-
=> #<Employee id: 1, company_id: 1, created_at: "2013-11-25 17:04:22", updated_at: "2013-11-25 17:05:05">
|
188
|
-
|
189
|
-
# triggers @employee.company.touch
|
190
|
-
>> @employee.touch
|
191
|
-
Employee/Company was touched
|
192
|
-
An Employee was touched
|
193
|
-
=> true
|
194
|
-
```
|
195
|
-
|
196
|
-
Running Callbacks
|
197
|
-
-----------------
|
198
|
-
|
199
|
-
The following methods trigger callbacks:
|
200
|
-
|
201
|
-
* `create`
|
202
|
-
* `create!`
|
203
|
-
* `decrement!`
|
204
|
-
* `destroy`
|
205
|
-
* `destroy!`
|
206
|
-
* `destroy_all`
|
207
|
-
* `increment!`
|
208
|
-
* `save`
|
209
|
-
* `save!`
|
210
|
-
* `save(validate: false)`
|
211
|
-
* `toggle!`
|
212
|
-
* `update_attribute`
|
213
|
-
* `update`
|
214
|
-
* `update!`
|
215
|
-
* `valid?`
|
216
|
-
|
217
|
-
Additionally, the `after_find` callback is triggered by the following finder methods:
|
218
|
-
|
219
|
-
* `all`
|
220
|
-
* `first`
|
221
|
-
* `find`
|
222
|
-
* `find_by`
|
223
|
-
* `find_by_*`
|
224
|
-
* `find_by_*!`
|
225
|
-
* `find_by_sql`
|
226
|
-
* `last`
|
227
|
-
|
228
|
-
The `after_initialize` callback is triggered every time a new object of the class is initialized.
|
229
|
-
|
230
|
-
NOTE: The `find_by_*` and `find_by_*!` methods are dynamic finders generated automatically for every attribute. Learn more about them at the [Dynamic finders section](active_record_querying.html#dynamic-finders)
|
231
|
-
|
232
|
-
Skipping Callbacks
|
233
|
-
------------------
|
234
|
-
|
235
|
-
Just as with validations, it is also possible to skip callbacks by using the following methods:
|
236
|
-
|
237
|
-
* `decrement`
|
238
|
-
* `decrement_counter`
|
239
|
-
* `delete`
|
240
|
-
* `delete_all`
|
241
|
-
* `increment`
|
242
|
-
* `increment_counter`
|
243
|
-
* `toggle`
|
244
|
-
* `touch`
|
245
|
-
* `update_column`
|
246
|
-
* `update_columns`
|
247
|
-
* `update_all`
|
248
|
-
* `update_counters`
|
249
|
-
|
250
|
-
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.
|
251
|
-
|
252
|
-
Halting Execution
|
253
|
-
-----------------
|
254
|
-
|
255
|
-
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.
|
256
|
-
|
257
|
-
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.
|
258
|
-
|
259
|
-
WARNING. Any exception that is not `ActiveRecord::Rollback` will be re-raised by Rails after the callback chain is halted. Raising an exception other than `ActiveRecord::Rollback` may break code that does not expect methods like `save` and `update_attributes` (which normally try to return `true` or `false`) to raise an exception.
|
260
|
-
|
261
|
-
Relational Callbacks
|
262
|
-
--------------------
|
263
|
-
|
264
|
-
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 `after_destroy` callback to the `User` model by way of its relationship to the `Article` model:
|
265
|
-
|
266
|
-
```ruby
|
267
|
-
class User < ActiveRecord::Base
|
268
|
-
has_many :articles, dependent: :destroy
|
269
|
-
end
|
270
|
-
|
271
|
-
class Article < ActiveRecord::Base
|
272
|
-
after_destroy :log_destroy_action
|
273
|
-
|
274
|
-
def log_destroy_action
|
275
|
-
puts 'Article destroyed'
|
276
|
-
end
|
277
|
-
end
|
278
|
-
|
279
|
-
>> user = User.first
|
280
|
-
=> #<User id: 1>
|
281
|
-
>> user.articles.create!
|
282
|
-
=> #<Article id: 1, user_id: 1>
|
283
|
-
>> user.destroy
|
284
|
-
Article destroyed
|
285
|
-
=> #<User id: 1>
|
286
|
-
```
|
287
|
-
|
288
|
-
Conditional Callbacks
|
289
|
-
---------------------
|
290
|
-
|
291
|
-
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 `:if` and `:unless` options, which can take a symbol, a string, a `Proc` or an `Array`. You may use the `:if` option when you want to specify under which conditions the callback **should** be called. If you want to specify the conditions under which the callback **should not** be called, then you may use the `:unless` option.
|
292
|
-
|
293
|
-
### Using `:if` and `:unless` with a `Symbol`
|
294
|
-
|
295
|
-
You can associate the `:if` and `:unless` options with a symbol corresponding to the name of a predicate method that will get called right before the callback. When using the `:if` option, the callback won't be executed if the predicate method returns false; when using the `:unless` 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.
|
296
|
-
|
297
|
-
```ruby
|
298
|
-
class Order < ActiveRecord::Base
|
299
|
-
before_save :normalize_card_number, if: :paid_with_card?
|
300
|
-
end
|
301
|
-
```
|
302
|
-
|
303
|
-
### Using `:if` and `:unless` with a String
|
304
|
-
|
305
|
-
You can also use a string that will be evaluated using `eval` and hence needs to contain valid Ruby code. You should use this option only when the string represents a really short condition:
|
306
|
-
|
307
|
-
```ruby
|
308
|
-
class Order < ActiveRecord::Base
|
309
|
-
before_save :normalize_card_number, if: "paid_with_card?"
|
310
|
-
end
|
311
|
-
```
|
312
|
-
|
313
|
-
### Using `:if` and `:unless` with a `Proc`
|
314
|
-
|
315
|
-
Finally, it is possible to associate `:if` and `:unless` with a `Proc` object. This option is best suited when writing short validation methods, usually one-liners:
|
316
|
-
|
317
|
-
```ruby
|
318
|
-
class Order < ActiveRecord::Base
|
319
|
-
before_save :normalize_card_number,
|
320
|
-
if: Proc.new { |order| order.paid_with_card? }
|
321
|
-
end
|
322
|
-
```
|
323
|
-
|
324
|
-
### Multiple Conditions for Callbacks
|
325
|
-
|
326
|
-
When writing conditional callbacks, it is possible to mix both `:if` and `:unless` in the same callback declaration:
|
327
|
-
|
328
|
-
```ruby
|
329
|
-
class Comment < ActiveRecord::Base
|
330
|
-
after_create :send_email_to_author, if: :author_wants_emails?,
|
331
|
-
unless: Proc.new { |comment| comment.article.ignore_comments? }
|
332
|
-
end
|
333
|
-
```
|
334
|
-
|
335
|
-
Callback Classes
|
336
|
-
----------------
|
337
|
-
|
338
|
-
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.
|
339
|
-
|
340
|
-
Here's an example where we create a class with an `after_destroy` callback for a `PictureFile` model:
|
341
|
-
|
342
|
-
```ruby
|
343
|
-
class PictureFileCallbacks
|
344
|
-
def after_destroy(picture_file)
|
345
|
-
if File.exist?(picture_file.filepath)
|
346
|
-
File.delete(picture_file.filepath)
|
347
|
-
end
|
348
|
-
end
|
349
|
-
end
|
350
|
-
```
|
351
|
-
|
352
|
-
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:
|
353
|
-
|
354
|
-
```ruby
|
355
|
-
class PictureFile < ActiveRecord::Base
|
356
|
-
after_destroy PictureFileCallbacks.new
|
357
|
-
end
|
358
|
-
```
|
359
|
-
|
360
|
-
Note that we needed to instantiate a new `PictureFileCallbacks` 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:
|
361
|
-
|
362
|
-
```ruby
|
363
|
-
class PictureFileCallbacks
|
364
|
-
def self.after_destroy(picture_file)
|
365
|
-
if File.exist?(picture_file.filepath)
|
366
|
-
File.delete(picture_file.filepath)
|
367
|
-
end
|
368
|
-
end
|
369
|
-
end
|
370
|
-
```
|
371
|
-
|
372
|
-
If the callback method is declared this way, it won't be necessary to instantiate a `PictureFileCallbacks` object.
|
373
|
-
|
374
|
-
```ruby
|
375
|
-
class PictureFile < ActiveRecord::Base
|
376
|
-
after_destroy PictureFileCallbacks
|
377
|
-
end
|
378
|
-
```
|
379
|
-
|
380
|
-
You can declare as many callbacks as you want inside your callback classes.
|
381
|
-
|
382
|
-
Transaction Callbacks
|
383
|
-
---------------------
|
384
|
-
|
385
|
-
There are two additional callbacks that are triggered by the completion of a database transaction: `after_commit` and `after_rollback`. These callbacks are very similar to the `after_save` 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.
|
386
|
-
|
387
|
-
Consider, for example, the previous example where the `PictureFile` model needs to delete a file after the corresponding record is destroyed. If anything raises an exception after the `after_destroy` 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 `picture_file_2` in the code below is not valid and the `save!` method raises an error.
|
388
|
-
|
389
|
-
```ruby
|
390
|
-
PictureFile.transaction do
|
391
|
-
picture_file_1.destroy
|
392
|
-
picture_file_2.save!
|
393
|
-
end
|
394
|
-
```
|
395
|
-
|
396
|
-
By using the `after_commit` callback we can account for this case.
|
397
|
-
|
398
|
-
```ruby
|
399
|
-
class PictureFile < ActiveRecord::Base
|
400
|
-
after_commit :delete_picture_file_from_disk, on: [:destroy]
|
401
|
-
|
402
|
-
def delete_picture_file_from_disk
|
403
|
-
if File.exist?(filepath)
|
404
|
-
File.delete(filepath)
|
405
|
-
end
|
406
|
-
end
|
407
|
-
end
|
408
|
-
```
|
409
|
-
|
410
|
-
NOTE: the `:on` option specifies when a callback will be fired. If you
|
411
|
-
don't supply the `:on` option the callback will fire for every action.
|
412
|
-
|
413
|
-
WARNING. The `after_commit` and `after_rollback` callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don't interfere with the other callbacks. As such, if your callback code could raise an exception, you'll need to rescue it and handle it appropriately within the callback.
|