@@ -34,7 +34,7 @@ as your own plain Ruby objects.
34
34
The term "Active Record" also refers to a software architecture pattern. Active
35
35
Record in Rails is an implementation of that pattern. It's also a description of
36
36
something called an [ Object Relational Mapping] [ ORM ] system. The below sections
37
- explain these terms:
37
+ explain these terms.
38
38
39
39
### The Active Record Pattern
40
40
@@ -107,12 +107,12 @@ This uses the [Active Support](active_support_core_extensions.html#pluralize)
107
107
[ pluralize] ( https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-pluralize ) method.
108
108
109
109
For class names composed of two or more words, the model class name will follow
110
- the Ruby conventions of using a UpperCamelCase name. The database table name, in
110
+ the Ruby conventions of using an UpperCamelCase name. The database table name, in
111
111
that case, will be a snake_case name. For example:
112
112
113
- * ` BookClub ` - is the model class, singular with the first letter of each word
113
+ * ` BookClub ` is the model class, singular with the first letter of each word
114
114
capitalized.
115
- * ` book_clubs ` - is the matching database table, plural with underscores
115
+ * ` book_clubs ` is the matching database table, plural with underscores
116
116
separating words.
117
117
118
118
Here are some more examples of model class names and corresponding table names:
@@ -153,9 +153,9 @@ Active Record instances:
153
153
* ` (association_name)_type ` - Stores the type for [ polymorphic
154
154
associations] ( association_basics.html#polymorphic-associations ) .
155
155
* ` (table_name)_count ` - Used to cache the number of belonging objects on
156
- associations. For example, a ` comments_count ` column in an ` Article ` class
157
- that has many instances of ` Comment ` will cache the number of existing
158
- comments for each article.
156
+ associations. For example, if ` Article ` s have many ` Comment ` s, a
157
+ ` comments_count ` column in the ` articles ` table will cache the number of
158
+ existing comments for each article.
159
159
160
160
NOTE: While these column names are optional, they are reserved by Active Record.
161
161
Steer clear of reserved keywords when naming your table's columns. For example,
184
184
This will create a ` Book ` model, mapped to a ` books ` table in the database,
185
185
where each column in the table is mapped to attributes of the ` Book ` class. An
186
186
instance of ` Book ` can represent a row in the ` books ` table. The ` books ` table
187
- can be created using an SQL statement like this:
187
+ with columns ` id ` , ` title ` , and ` author ` , can be created using an SQL statement
188
+ like this:
188
189
189
190
``` sql
190
191
CREATE TABLE books (
@@ -195,9 +196,9 @@ CREATE TABLE books (
195
196
);
196
197
```
197
198
198
- Database tables in Rails are typically created using [ Active Record
199
- Migrations] ( #migrations ) and not raw SQL. A migration for the ` books ` table
200
- above can be generated like this:
199
+ However, that is not how you do it normally in Rails. Database tables in Rails
200
+ are typically created using [ Active Record Migrations] ( #migrations ) and not raw
201
+ SQL. A migration for the ` books ` table above can be generated like this:
201
202
202
203
``` bash
203
204
$ bin/rails generate migration CreateBooks title:string author:string
@@ -208,7 +209,7 @@ and results in this:
208
209
``` ruby
209
210
# Note:
210
211
# The `id` column, as the primary key, is automatically created by convention.
211
- # Columns `created_at` and `updated_at` are added by `t.timestamps` line .
212
+ # Columns `created_at` and `updated_at` are added by `t.timestamps`.
212
213
213
214
# /db/migrate/20240220143807_create_books.rb
214
215
class CreateBooks < ActiveRecord ::Migration
@@ -223,10 +224,10 @@ class CreateBooks < ActiveRecord::Migration
223
224
end
224
225
```
225
226
226
- The SQL as well as the migration above declare a table with three columns: ` id ` ,
227
- ` title ` , and ` author ` . Each row of this table can be represented by an instance
228
- of the ` Book ` class with the same three attributes: ` id ` , ` title ` , and ` author ` .
229
- You can access a book's attributes like this:
227
+ That migration creates columns ` id ` , ` title ` , ` author ` , ` created_at ` and
228
+ ` updated_at ` . Each row of this table can be represented by an instance of the
229
+ ` Book ` class with the same attributes: ` id ` , ` title ` , ` author ` , ` created_at ` ,
230
+ and ` updated_at ` . You can access a book's attributes like this:
230
231
231
232
``` irb
232
233
irb> book = Book.new
@@ -239,9 +240,10 @@ irb> book.title
239
240
```
240
241
241
242
NOTE: You can generate the Active Record model class as well as a matching
242
- migration with this command `bin/rails generate model Book title: string
243
- author: string ` . This creates both ` /app/models/book.rb` and
244
- ` /db/migrate/20240220143807_create_books.rb ` files.
243
+ migration with the command `bin/rails generate model Book title: string
244
+ author: string ` . This creates the files ` /app/models/book.rb`,
245
+ ` /db/migrate/20240220143807_create_books.rb ` , and a couple others for testing
246
+ purposes.
245
247
246
248
### Creating Namespaced Models
247
249
@@ -251,7 +253,7 @@ folder and namespace. For example, `order.rb` and `review.rb` under
251
253
` app/models/product ` with ` Product::Order ` and ` Product::Review ` class names,
252
254
respectively. You can create namespaced models with Active Record.
253
255
254
- In the case where ` Product ` module does not already exist, the ` generate `
256
+ In the case where the ` Product ` module does not already exist, the ` generate `
255
257
command will create everything like this:
256
258
257
259
``` bash
@@ -265,7 +267,7 @@ $ bin/rails generate model Product::Order
265
267
create test/fixtures/product/orders.yml
266
268
```
267
269
268
- In the case where ` Product ` module already exists, you will be asked to resolve
270
+ If the ` Product ` module already exists, you will be asked to resolve
269
271
the conflict:
270
272
271
273
``` bash
@@ -371,7 +373,7 @@ CRUD: Reading and Writing Data
371
373
------------------------------
372
374
373
375
CRUD is an acronym for the four verbs we use to operate on data: ** C** reate,
374
- ** R** ead, ** U** pdate and ** D** elete. Active Record automatically creates methods
376
+ ** R** ead, ** U** pdate, and ** D** elete. Active Record automatically creates methods
375
377
to allow you to read and manipulate data stored in your application's database
376
378
tables.
377
379
@@ -386,8 +388,9 @@ statements.
386
388
### Create
387
389
388
390
Active Record objects can be created from a hash, a block, or have their
389
- attributes manually set after creation. The ` new ` method will return a new
390
- object while ` create ` will return the object and save it to the database.
391
+ attributes manually set after creation. The ` new ` method will return a new,
392
+ non-persisted object, while ` create ` will save the object to the database and
393
+ return it.
391
394
392
395
For example, given a ` Book ` model with attributes of ` title ` and ` author ` , the
393
396
` create ` method call will create an object and save a new record to the
@@ -438,7 +441,7 @@ The resulting SQL statement from both `book.save` and `Book.create` look
438
441
something like this:
439
442
440
443
``` sql
441
- /* Note that `created_at` and `updated_at` are automatically set */
444
+ /* Note that `created_at` and `updated_at` are automatically set. */
442
445
443
446
INSERT INTO " books" (" title" , " author" , " created_at" , " updated_at" ) VALUES (?, ?, ?, ?) RETURNING " id" [[" title" , " Metaprogramming Ruby 2" ], [" author" , " Paolo Perrotta" ], [" created_at" , " 2024-02-22 20:01:18.469952" ], [" updated_at" , " 2024-02-22 20:01:18.469952" ]]
444
447
```
@@ -450,10 +453,10 @@ query a single record or multiple records, filter them by any attribute, order
450
453
them, group them, select specific fields, and do anything you can do with SQL.
451
454
452
455
``` ruby
453
- # Return a collection with all books
456
+ # Return a collection with all books.
454
457
books = Book .all
455
458
456
- # Return a single book
459
+ # Return a single book.
457
460
first_book = Book .first
458
461
last_book = Book .last
459
462
book = Book .take
@@ -495,7 +498,7 @@ SELECT "books".* FROM "books" WHERE "books"."id" = ? LIMIT ? [["id", 42], ["LIM
495
498
```
496
499
497
500
``` ruby
498
- # Find all books with a given an author, sort by created_at in reverse chronological order
501
+ # Find all books with a given an author, sort by created_at in reverse chronological order.
499
502
Book .where(author: " Douglas Adams" ).order(created_at: :desc )
500
503
```
501
504
@@ -530,7 +533,7 @@ book.update(title: "The Lord of the Rings: The Fellowship of the Ring")
530
533
the ` update ` results in the following SQL:
531
534
532
535
``` sql
533
- /* Note that `updated_at` is automatically set */
536
+ /* Note that `updated_at` is automatically set. */
534
537
535
538
UPDATE " books" SET " title" = ?, " updated_at" = ? WHERE " books" ." id" = ? [[" title" , " The Lord of the Rings: The Fellowship of the Ring" ], [" updated_at" , " 2024-02-22 20:51:13.487064" ], [" id" , 104 ]]
536
539
```
@@ -565,10 +568,10 @@ If you'd like to delete several records in bulk, you may use `destroy_by`
565
568
or ` destroy_all ` method:
566
569
567
570
``` ruby
568
- # Find and delete all books by Douglas Adams
571
+ # Find and delete all books by Douglas Adams.
569
572
Book .destroy_by(author: " Douglas Adams" )
570
573
571
- # Delete all books
574
+ # Delete all books.
572
575
Book .destroy_all
573
576
```
574
577
@@ -684,8 +687,8 @@ class Author < ApplicationRecord
684
687
end
685
688
```
686
689
687
- The Author class now has methods to add and remove books to an author, and much
688
- more.
690
+ The ` Author ` class now has methods to add and remove books to an author, and
691
+ much more.
689
692
690
693
You can learn more about associations in the [ Active Record Associations
691
694
guide] ( association_basics.html ) .
0 commit comments