rails 4.2.11.3 → 5.0.7.1
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/README.md +14 -10
- metadata +38 -244
- 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/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 -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).
|