rails 4.2.11.3 → 5.0.0.beta1
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +5 -5
- data/README.md +11 -7
- metadata +38 -237
- data/guides/CHANGELOG.md +0 -113
- data/guides/Rakefile +0 -92
- 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.rb +0 -63
- 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.rb +0 -167
- data/guides/rails_guides/markdown/renderer.rb +0 -82
- 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 -3856
- 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 -1070
- 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 -1226
- 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 -335
- 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,374 +0,0 @@
|
|
1
|
-
Active Record Basics
|
2
|
-
====================
|
3
|
-
|
4
|
-
This guide is an introduction to Active Record.
|
5
|
-
|
6
|
-
After reading this guide, you will know:
|
7
|
-
|
8
|
-
* What Object Relational Mapping and Active Record are and how they are used in
|
9
|
-
Rails.
|
10
|
-
* How Active Record fits into the Model-View-Controller paradigm.
|
11
|
-
* How to use Active Record models to manipulate data stored in a relational
|
12
|
-
database.
|
13
|
-
* Active Record schema naming conventions.
|
14
|
-
* The concepts of database migrations, validations and callbacks.
|
15
|
-
|
16
|
-
--------------------------------------------------------------------------------
|
17
|
-
|
18
|
-
What is Active Record?
|
19
|
-
----------------------
|
20
|
-
|
21
|
-
Active Record is the M in [MVC](getting_started.html#the-mvc-architecture) - the
|
22
|
-
model - which is the layer of the system responsible for representing business
|
23
|
-
data and logic. Active Record facilitates the creation and use of business
|
24
|
-
objects whose data requires persistent storage to a database. It is an
|
25
|
-
implementation of the Active Record pattern which itself is a description of an
|
26
|
-
Object Relational Mapping system.
|
27
|
-
|
28
|
-
### The Active Record Pattern
|
29
|
-
|
30
|
-
[Active Record was described by Martin Fowler](http://www.martinfowler.com/eaaCatalog/activeRecord.html)
|
31
|
-
in his book _Patterns of Enterprise Application Architecture_. In
|
32
|
-
Active Record, objects carry both persistent data and behavior which
|
33
|
-
operates on that data. Active Record takes the opinion that ensuring
|
34
|
-
data access logic as part of the object will educate users of that
|
35
|
-
object on how to write to and read from the database.
|
36
|
-
|
37
|
-
### Object Relational Mapping
|
38
|
-
|
39
|
-
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is
|
40
|
-
a technique that connects the rich objects of an application to tables in
|
41
|
-
a relational database management system. Using ORM, the properties and
|
42
|
-
relationships of the objects in an application can be easily stored and
|
43
|
-
retrieved from a database without writing SQL statements directly and with less
|
44
|
-
overall database access code.
|
45
|
-
|
46
|
-
### Active Record as an ORM Framework
|
47
|
-
|
48
|
-
Active Record gives us several mechanisms, the most important being the ability
|
49
|
-
to:
|
50
|
-
|
51
|
-
* Represent models and their data.
|
52
|
-
* Represent associations between these models.
|
53
|
-
* Represent inheritance hierarchies through related models.
|
54
|
-
* Validate models before they get persisted to the database.
|
55
|
-
* Perform database operations in an object-oriented fashion.
|
56
|
-
|
57
|
-
Convention over Configuration in Active Record
|
58
|
-
----------------------------------------------
|
59
|
-
|
60
|
-
When writing applications using other programming languages or frameworks, it
|
61
|
-
may be necessary to write a lot of configuration code. This is particularly true
|
62
|
-
for ORM frameworks in general. However, if you follow the conventions adopted by
|
63
|
-
Rails, you'll need to write very little configuration (in some case no
|
64
|
-
configuration at all) when creating Active Record models. The idea is that if
|
65
|
-
you configure your applications in the very same way most of the time then this
|
66
|
-
should be the default way. Thus, explicit configuration would be needed
|
67
|
-
only in those cases where you can't follow the standard convention.
|
68
|
-
|
69
|
-
### Naming Conventions
|
70
|
-
|
71
|
-
By default, Active Record uses some naming conventions to find out how the
|
72
|
-
mapping between models and database tables should be created. Rails will
|
73
|
-
pluralize your class names to find the respective database table. So, for
|
74
|
-
a class `Book`, you should have a database table called **books**. The Rails
|
75
|
-
pluralization mechanisms are very powerful, being capable to pluralize (and
|
76
|
-
singularize) both regular and irregular words. When using class names composed
|
77
|
-
of two or more words, the model class name should follow the Ruby conventions,
|
78
|
-
using the CamelCase form, while the table name must contain the words separated
|
79
|
-
by underscores. Examples:
|
80
|
-
|
81
|
-
* Database Table - Plural with underscores separating words (e.g., `book_clubs`).
|
82
|
-
* Model Class - Singular with the first letter of each word capitalized (e.g.,
|
83
|
-
`BookClub`).
|
84
|
-
|
85
|
-
| Model / Class | Table / Schema |
|
86
|
-
| ---------------- | -------------- |
|
87
|
-
| `Article` | `articles` |
|
88
|
-
| `LineItem` | `line_items` |
|
89
|
-
| `Deer` | `deers` |
|
90
|
-
| `Mouse` | `mice` |
|
91
|
-
| `Person` | `people` |
|
92
|
-
|
93
|
-
|
94
|
-
### Schema Conventions
|
95
|
-
|
96
|
-
Active Record uses naming conventions for the columns in database tables,
|
97
|
-
depending on the purpose of these columns.
|
98
|
-
|
99
|
-
* **Foreign keys** - These fields should be named following the pattern
|
100
|
-
`singularized_table_name_id` (e.g., `item_id`, `order_id`). These are the
|
101
|
-
fields that Active Record will look for when you create associations between
|
102
|
-
your models.
|
103
|
-
* **Primary keys** - By default, Active Record will use an integer column named
|
104
|
-
`id` as the table's primary key. When using [Active Record
|
105
|
-
Migrations](migrations.html) to create your tables, this column will be
|
106
|
-
automatically created.
|
107
|
-
|
108
|
-
There are also some optional column names that will add additional features
|
109
|
-
to Active Record instances:
|
110
|
-
|
111
|
-
* `created_at` - Automatically gets set to the current date and time when the
|
112
|
-
record is first created.
|
113
|
-
* `updated_at` - Automatically gets set to the current date and time whenever
|
114
|
-
the record is updated.
|
115
|
-
* `lock_version` - Adds [optimistic
|
116
|
-
locking](http://api.rubyonrails.org/classes/ActiveRecord/Locking.html) to
|
117
|
-
a model.
|
118
|
-
* `type` - Specifies that the model uses [Single Table
|
119
|
-
Inheritance](http://api.rubyonrails.org/classes/ActiveRecord/Base.html#class-ActiveRecord::Base-label-Single+table+inheritance).
|
120
|
-
* `(association_name)_type` - Stores the type for
|
121
|
-
[polymorphic associations](association_basics.html#polymorphic-associations).
|
122
|
-
* `(table_name)_count` - Used to cache the number of belonging objects on
|
123
|
-
associations. For example, a `comments_count` column in a `Articles` class that
|
124
|
-
has many instances of `Comment` will cache the number of existent comments
|
125
|
-
for each article.
|
126
|
-
|
127
|
-
NOTE: While these column names are optional, they are in fact reserved by Active Record. Steer clear of reserved keywords unless you want the extra functionality. For example, `type` is a reserved keyword used to designate a table using Single Table Inheritance (STI). If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling.
|
128
|
-
|
129
|
-
Creating Active Record Models
|
130
|
-
-----------------------------
|
131
|
-
|
132
|
-
It is very easy to create Active Record models. All you have to do is to
|
133
|
-
subclass the `ActiveRecord::Base` class and you're good to go:
|
134
|
-
|
135
|
-
```ruby
|
136
|
-
class Product < ActiveRecord::Base
|
137
|
-
end
|
138
|
-
```
|
139
|
-
|
140
|
-
This will create a `Product` model, mapped to a `products` table at the
|
141
|
-
database. By doing this you'll also have the ability to map the columns of each
|
142
|
-
row in that table with the attributes of the instances of your model. Suppose
|
143
|
-
that the `products` table was created using an SQL sentence like:
|
144
|
-
|
145
|
-
```sql
|
146
|
-
CREATE TABLE products (
|
147
|
-
id int(11) NOT NULL auto_increment,
|
148
|
-
name varchar(255),
|
149
|
-
PRIMARY KEY (id)
|
150
|
-
);
|
151
|
-
```
|
152
|
-
|
153
|
-
Following the table schema above, you would be able to write code like the
|
154
|
-
following:
|
155
|
-
|
156
|
-
```ruby
|
157
|
-
p = Product.new
|
158
|
-
p.name = "Some Book"
|
159
|
-
puts p.name # "Some Book"
|
160
|
-
```
|
161
|
-
|
162
|
-
Overriding the Naming Conventions
|
163
|
-
---------------------------------
|
164
|
-
|
165
|
-
What if you need to follow a different naming convention or need to use your
|
166
|
-
Rails application with a legacy database? No problem, you can easily override
|
167
|
-
the default conventions.
|
168
|
-
|
169
|
-
You can use the `ActiveRecord::Base.table_name=` method to specify the table
|
170
|
-
name that should be used:
|
171
|
-
|
172
|
-
```ruby
|
173
|
-
class Product < ActiveRecord::Base
|
174
|
-
self.table_name = "my_products"
|
175
|
-
end
|
176
|
-
```
|
177
|
-
|
178
|
-
If you do so, you will have to define manually the class name that is hosting
|
179
|
-
the fixtures (my_products.yml) using the `set_fixture_class` method in your test
|
180
|
-
definition:
|
181
|
-
|
182
|
-
```ruby
|
183
|
-
class ProductTest < ActiveSupport::TestCase
|
184
|
-
set_fixture_class my_products: Product
|
185
|
-
fixtures :my_products
|
186
|
-
...
|
187
|
-
end
|
188
|
-
```
|
189
|
-
|
190
|
-
It's also possible to override the column that should be used as the table's
|
191
|
-
primary key using the `ActiveRecord::Base.primary_key=` method:
|
192
|
-
|
193
|
-
```ruby
|
194
|
-
class Product < ActiveRecord::Base
|
195
|
-
self.primary_key = "product_id"
|
196
|
-
end
|
197
|
-
```
|
198
|
-
|
199
|
-
CRUD: Reading and Writing Data
|
200
|
-
------------------------------
|
201
|
-
|
202
|
-
CRUD is an acronym for the four verbs we use to operate on data: **C**reate,
|
203
|
-
**R**ead, **U**pdate and **D**elete. Active Record automatically creates methods
|
204
|
-
to allow an application to read and manipulate data stored within its tables.
|
205
|
-
|
206
|
-
### Create
|
207
|
-
|
208
|
-
Active Record objects can be created from a hash, a block or have their
|
209
|
-
attributes manually set after creation. The `new` method will return a new
|
210
|
-
object while `create` will return the object and save it to the database.
|
211
|
-
|
212
|
-
For example, given a model `User` with attributes of `name` and `occupation`,
|
213
|
-
the `create` method call will create and save a new record into the database:
|
214
|
-
|
215
|
-
```ruby
|
216
|
-
user = User.create(name: "David", occupation: "Code Artist")
|
217
|
-
```
|
218
|
-
|
219
|
-
Using the `new` method, an object can be instantiated without being saved:
|
220
|
-
|
221
|
-
```ruby
|
222
|
-
user = User.new
|
223
|
-
user.name = "David"
|
224
|
-
user.occupation = "Code Artist"
|
225
|
-
```
|
226
|
-
|
227
|
-
A call to `user.save` will commit the record to the database.
|
228
|
-
|
229
|
-
Finally, if a block is provided, both `create` and `new` will yield the new
|
230
|
-
object to that block for initialization:
|
231
|
-
|
232
|
-
```ruby
|
233
|
-
user = User.new do |u|
|
234
|
-
u.name = "David"
|
235
|
-
u.occupation = "Code Artist"
|
236
|
-
end
|
237
|
-
```
|
238
|
-
|
239
|
-
### Read
|
240
|
-
|
241
|
-
Active Record provides a rich API for accessing data within a database. Below
|
242
|
-
are a few examples of different data access methods provided by Active Record.
|
243
|
-
|
244
|
-
```ruby
|
245
|
-
# return a collection with all users
|
246
|
-
users = User.all
|
247
|
-
```
|
248
|
-
|
249
|
-
```ruby
|
250
|
-
# return the first user
|
251
|
-
user = User.first
|
252
|
-
```
|
253
|
-
|
254
|
-
```ruby
|
255
|
-
# return the first user named David
|
256
|
-
david = User.find_by(name: 'David')
|
257
|
-
```
|
258
|
-
|
259
|
-
```ruby
|
260
|
-
# find all users named David who are Code Artists and sort by created_at in reverse chronological order
|
261
|
-
users = User.where(name: 'David', occupation: 'Code Artist').order(created_at: :desc)
|
262
|
-
```
|
263
|
-
|
264
|
-
You can learn more about querying an Active Record model in the [Active Record
|
265
|
-
Query Interface](active_record_querying.html) guide.
|
266
|
-
|
267
|
-
### Update
|
268
|
-
|
269
|
-
Once an Active Record object has been retrieved, its attributes can be modified
|
270
|
-
and it can be saved to the database.
|
271
|
-
|
272
|
-
```ruby
|
273
|
-
user = User.find_by(name: 'David')
|
274
|
-
user.name = 'Dave'
|
275
|
-
user.save
|
276
|
-
```
|
277
|
-
|
278
|
-
A shorthand for this is to use a hash mapping attribute names to the desired
|
279
|
-
value, like so:
|
280
|
-
|
281
|
-
```ruby
|
282
|
-
user = User.find_by(name: 'David')
|
283
|
-
user.update(name: 'Dave')
|
284
|
-
```
|
285
|
-
|
286
|
-
This is most useful when updating several attributes at once. If, on the other
|
287
|
-
hand, you'd like to update several records in bulk, you may find the
|
288
|
-
`update_all` class method useful:
|
289
|
-
|
290
|
-
```ruby
|
291
|
-
User.update_all "max_login_attempts = 3, must_change_password = 'true'"
|
292
|
-
```
|
293
|
-
|
294
|
-
### Delete
|
295
|
-
|
296
|
-
Likewise, once retrieved an Active Record object can be destroyed which removes
|
297
|
-
it from the database.
|
298
|
-
|
299
|
-
```ruby
|
300
|
-
user = User.find_by(name: 'David')
|
301
|
-
user.destroy
|
302
|
-
```
|
303
|
-
|
304
|
-
Validations
|
305
|
-
-----------
|
306
|
-
|
307
|
-
Active Record allows you to validate the state of a model before it gets written
|
308
|
-
into the database. There are several methods that you can use to check your
|
309
|
-
models and validate that an attribute value is not empty, is unique and not
|
310
|
-
already in the database, follows a specific format and many more.
|
311
|
-
|
312
|
-
Validation is a very important issue to consider when persisting to the database, so
|
313
|
-
the methods `save` and `update` take it into account when
|
314
|
-
running: they return `false` when validation fails and they didn't actually
|
315
|
-
perform any operation on the database. All of these have a bang counterpart (that
|
316
|
-
is, `save!` and `update!`), which are stricter in that
|
317
|
-
they raise the exception `ActiveRecord::RecordInvalid` if validation fails.
|
318
|
-
A quick example to illustrate:
|
319
|
-
|
320
|
-
```ruby
|
321
|
-
class User < ActiveRecord::Base
|
322
|
-
validates :name, presence: true
|
323
|
-
end
|
324
|
-
|
325
|
-
user = User.new
|
326
|
-
user.save # => false
|
327
|
-
user.save! # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
|
328
|
-
```
|
329
|
-
|
330
|
-
You can learn more about validations in the [Active Record Validations
|
331
|
-
guide](active_record_validations.html).
|
332
|
-
|
333
|
-
Callbacks
|
334
|
-
---------
|
335
|
-
|
336
|
-
Active Record callbacks allow you to attach code to certain events in the
|
337
|
-
life-cycle of your models. This enables you to add behavior to your models by
|
338
|
-
transparently executing code when those events occur, like when you create a new
|
339
|
-
record, update it, destroy it and so on. You can learn more about callbacks in
|
340
|
-
the [Active Record Callbacks guide](active_record_callbacks.html).
|
341
|
-
|
342
|
-
Migrations
|
343
|
-
----------
|
344
|
-
|
345
|
-
Rails provides a domain-specific language for managing a database schema called
|
346
|
-
migrations. Migrations are stored in files which are executed against any
|
347
|
-
database that Active Record supports using `rake`. Here's a migration that
|
348
|
-
creates a table:
|
349
|
-
|
350
|
-
```ruby
|
351
|
-
class CreatePublications < ActiveRecord::Migration
|
352
|
-
def change
|
353
|
-
create_table :publications do |t|
|
354
|
-
t.string :title
|
355
|
-
t.text :description
|
356
|
-
t.references :publication_type
|
357
|
-
t.integer :publisher_id
|
358
|
-
t.string :publisher_type
|
359
|
-
t.boolean :single_issue
|
360
|
-
|
361
|
-
t.timestamps null: false
|
362
|
-
end
|
363
|
-
add_index :publications, :publication_type_id
|
364
|
-
end
|
365
|
-
end
|
366
|
-
```
|
367
|
-
|
368
|
-
Rails keeps track of which files have been committed to the database and
|
369
|
-
provides rollback features. To actually create the table, you'd run `rake db:migrate`
|
370
|
-
and to roll it back, `rake db:rollback`.
|
371
|
-
|
372
|
-
Note that the above code is database-agnostic: it will run in MySQL,
|
373
|
-
PostgreSQL, Oracle and others. You can learn more about migrations in the
|
374
|
-
[Active Record Migrations guide](migrations.html).
|
@@ -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.
|