rails 4.0.0.beta1 → 4.0.0.rc1
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 +4 -4
- data/README.md +78 -0
- data/guides/CHANGELOG.md +3 -0
- data/guides/assets/images/getting_started/unknown_action_create_for_posts.png +0 -0
- data/guides/bug_report_templates/active_record_gem.rb +37 -0
- data/guides/bug_report_templates/active_record_master.rb +48 -0
- data/guides/code/getting_started/Gemfile +16 -11
- data/guides/code/getting_started/app/controllers/comments_controller.rb +2 -2
- data/guides/code/getting_started/app/controllers/posts_controller.rb +2 -2
- data/guides/code/getting_started/config/application.rb +3 -2
- data/guides/code/getting_started/config/initializers/session_store.rb +1 -1
- data/guides/code/getting_started/config/routes.rb +2 -2
- data/guides/code/getting_started/public/404.html +41 -10
- data/guides/code/getting_started/public/422.html +42 -10
- data/guides/code/getting_started/public/500.html +41 -10
- data/guides/rails_guides/markdown/renderer.rb +1 -1
- data/guides/source/2_2_release_notes.md +15 -15
- data/guides/source/4_0_release_notes.md +1 -7
- data/guides/source/action_controller_overview.md +176 -22
- data/guides/source/action_mailer_basics.md +246 -141
- data/guides/source/action_view_overview.md +3 -8
- data/guides/source/active_record_basics.md +98 -95
- data/guides/source/active_record_querying.md +90 -17
- data/guides/source/active_record_validations.md +41 -0
- data/guides/source/active_support_core_extensions.md +23 -3
- data/guides/source/active_support_instrumentation.md +6 -6
- data/guides/source/asset_pipeline.md +1 -1
- data/guides/source/association_basics.md +34 -10
- data/guides/source/caching_with_rails.md +2 -7
- data/guides/source/command_line.md +7 -7
- data/guides/source/configuring.md +3 -3
- data/guides/source/contributing_to_ruby_on_rails.md +38 -5
- data/guides/source/credits.html.erb +1 -1
- data/guides/source/debugging_rails_applications.md +19 -22
- data/guides/source/development_dependencies_install.md +2 -2
- data/guides/source/documents.yaml +5 -1
- data/guides/source/engines.md +21 -16
- data/guides/source/form_helpers.md +28 -7
- data/guides/source/generators.md +2 -2
- data/guides/source/getting_started.md +14 -13
- data/guides/source/i18n.md +22 -0
- data/guides/source/initialization.md +1 -1
- data/guides/source/layouts_and_rendering.md +60 -4
- data/guides/source/migrations.md +27 -2
- data/guides/source/rails_application_templates.md +11 -11
- data/guides/source/rails_on_rack.md +9 -6
- data/guides/source/routing.md +19 -3
- data/guides/source/ruby_on_rails_guides_guidelines.md +1 -1
- data/guides/source/security.md +2 -2
- data/guides/source/testing.md +106 -85
- data/guides/source/upgrading_ruby_on_rails.md +112 -9
- data/guides/source/working_with_javascript_in_rails.md +1 -0
- metadata +17 -16
- data/README.rdoc +0 -77
- data/guides/code/getting_started/app/assets/images/rails.png +0 -0
@@ -172,7 +172,7 @@ That code will pull in the partial from `app/views/shared/_menu.html.erb`.
|
|
172
172
|
|
173
173
|
#### Using Partials to simplify Views
|
174
174
|
|
175
|
-
One way to use partials is to treat them as the equivalent of subroutines
|
175
|
+
One way to use partials is to treat them as the equivalent of subroutines; a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looks like this:
|
176
176
|
|
177
177
|
```html+erb
|
178
178
|
<%= render "shared/ad_banner" %>
|
@@ -269,12 +269,7 @@ Rails will render the `_product_ruler` partial (with no data passed to it) betwe
|
|
269
269
|
|
270
270
|
### Layouts
|
271
271
|
|
272
|
-
|
273
|
-
|
274
|
-
Using Templates, Partials and Layouts "The Rails Way"
|
275
|
-
--------------------------------------------------------
|
276
|
-
|
277
|
-
TODO...
|
272
|
+
Layouts can be used to render a common view template around the results of Rails controller actions. Typically, every Rails has a couple of overall layouts that most pages are rendered within. For example, a site might have a layout for a logged in user, and a layout for the marketing or sales side of the site. The logged in user layout might include top-level navigation that should be present across many controller actions. The sales layout for a SaaS app might include top-level navigation for things like "Pricing" and "Contact Us." You would expect each layout to have a different look and feel. You can read more details about Layouts in the [Layouts and Rendering in Rails](layouts_and_rendering.html) guide.
|
278
273
|
|
279
274
|
Partial Layouts
|
280
275
|
---------------
|
@@ -492,7 +487,7 @@ image_path("edit.png") # => /assets/edit-2d1a2db63fc738690021fedb5a65b68e.png
|
|
492
487
|
|
493
488
|
#### image_url
|
494
489
|
|
495
|
-
Computes the url to an image asset in the `app/
|
490
|
+
Computes the url to an image asset in the `app/assets/images` directory. This will call `image_path` internally and merge with your current host or your asset host.
|
496
491
|
|
497
492
|
```ruby
|
498
493
|
image_url("edit.png") # => http://www.example.com/assets/edit.png
|
@@ -1,14 +1,14 @@
|
|
1
1
|
Active Record Basics
|
2
2
|
====================
|
3
|
-
|
3
|
+
|
4
4
|
This guide is an introduction to Active Record.
|
5
5
|
|
6
6
|
After reading this guide, you will know:
|
7
7
|
|
8
|
-
* What Object Relational Mapping and Active Record are and how they are used in
|
8
|
+
* What Object Relational Mapping and Active Record are and how they are used in
|
9
9
|
Rails.
|
10
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
|
11
|
+
* How to use Active Record models to manipulate data stored in a relational
|
12
12
|
database.
|
13
13
|
* Active Record schema naming conventions.
|
14
14
|
* The concepts of database migrations, validations and callbacks.
|
@@ -18,33 +18,34 @@ After reading this guide, you will know:
|
|
18
18
|
What is Active Record?
|
19
19
|
----------------------
|
20
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
|
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
26
|
Object Relational Mapping system.
|
27
27
|
|
28
28
|
### The Active Record Pattern
|
29
29
|
|
30
|
-
Active Record was described by Martin Fowler
|
31
|
-
|
32
|
-
|
33
|
-
|
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 is part of the object will educate users of that
|
34
35
|
object on how to write to and read from the database.
|
35
36
|
|
36
37
|
### Object Relational Mapping
|
37
38
|
|
38
|
-
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is
|
39
|
-
a technique that connects the rich objects of an application to tables in
|
40
|
-
a relational database management system. Using ORM, the properties and
|
41
|
-
relationships of the objects in an application can be easily stored and
|
42
|
-
retrieved from a database without writing SQL statements directly and with less
|
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
|
43
44
|
overall database access code.
|
44
45
|
|
45
46
|
### Active Record as an ORM Framework
|
46
47
|
|
47
|
-
Active Record gives us several mechanisms, the most important being the ability
|
48
|
+
Active Record gives us several mechanisms, the most important being the ability
|
48
49
|
to:
|
49
50
|
|
50
51
|
* Represent models and their data
|
@@ -56,29 +57,29 @@ to:
|
|
56
57
|
Convention over Configuration in Active Record
|
57
58
|
----------------------------------------------
|
58
59
|
|
59
|
-
When writing applications using other programming languages or frameworks, it
|
60
|
-
may be necessary to write a lot of configuration code. This is particularly true
|
61
|
-
for ORM frameworks in general. However, if you follow the conventions adopted by
|
62
|
-
Rails, you'll need to write very little configuration (in some case no
|
63
|
-
configuration at all) when creating Active Record models. The idea is that if
|
64
|
-
you configure your applications in the very same way most of the times then this
|
65
|
-
should be the default way. In this cases, explicit configuration would be needed
|
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 times then this
|
66
|
+
should be the default way. In this cases, explicit configuration would be needed
|
66
67
|
only in those cases where you can't follow the conventions for any reason.
|
67
68
|
|
68
69
|
### Naming Conventions
|
69
70
|
|
70
|
-
By default, Active Record uses some naming conventions to find out how the
|
71
|
-
mapping between models and database tables should be created. Rails will
|
72
|
-
pluralize your class names to find the respective database table. So, for
|
73
|
-
a class `Book`, you should have a database table called **books**. The Rails
|
74
|
-
pluralization mechanisms are very powerful, being capable to pluralize (and
|
75
|
-
singularize) both regular and irregular words. When using class names composed
|
76
|
-
of two or more words, the model class name should follow the Ruby conventions,
|
77
|
-
using the CamelCase form, while the table name must contain the words separated
|
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
|
78
79
|
by underscores. Examples:
|
79
80
|
|
80
81
|
* Database Table - Plural with underscores separating words (e.g., `book_clubs`)
|
81
|
-
* Model Class - Singular with the first letter of each word capitalized (e.g.,
|
82
|
+
* Model Class - Singular with the first letter of each word capitalized (e.g.,
|
82
83
|
`BookClub`)
|
83
84
|
|
84
85
|
| Model / Class | Table / Schema |
|
@@ -92,33 +93,35 @@ by underscores. Examples:
|
|
92
93
|
|
93
94
|
### Schema Conventions
|
94
95
|
|
95
|
-
Active Record uses naming conventions for the columns in database tables,
|
96
|
+
Active Record uses naming conventions for the columns in database tables,
|
96
97
|
depending on the purpose of these columns.
|
97
98
|
|
98
|
-
* **Foreign keys** - These fields should be named following the pattern
|
99
|
-
`singularized_table_name_id` (e.g., `item_id`, `order_id`). These are the
|
100
|
-
fields that Active Record will look for when you create associations between
|
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
|
101
102
|
your models.
|
102
|
-
* **Primary keys** - By default, Active Record will use an integer column named
|
103
|
-
`id` as the table's primary key. When using [Rails
|
104
|
-
Migrations](migrations.html) to create your tables, this column will be
|
103
|
+
* **Primary keys** - By default, Active Record will use an integer column named
|
104
|
+
`id` as the table's primary key. When using [Rails
|
105
|
+
Migrations](migrations.html) to create your tables, this column will be
|
105
106
|
automatically created.
|
106
107
|
|
107
|
-
There are also some optional column names that will create additional features
|
108
|
+
There are also some optional column names that will create additional features
|
108
109
|
to Active Record instances:
|
109
110
|
|
110
|
-
* `created_at` - Automatically gets set to the current date and time when the
|
111
|
+
* `created_at` - Automatically gets set to the current date and time when the
|
111
112
|
record is first created.
|
112
|
-
* `updated_at` - Automatically gets set to the current date and time whenever
|
113
|
+
* `updated_at` - Automatically gets set to the current date and time whenever
|
113
114
|
the record is updated.
|
114
|
-
* `lock_version` - Adds [optimistic
|
115
|
-
locking](http://api.rubyonrails.org/classes/ActiveRecord/Locking.html) to
|
115
|
+
* `lock_version` - Adds [optimistic
|
116
|
+
locking](http://api.rubyonrails.org/classes/ActiveRecord/Locking.html) to
|
116
117
|
a model.
|
117
|
-
* `type` - Specifies that the model uses [Single Table
|
118
|
+
* `type` - Specifies that the model uses [Single Table
|
118
119
|
Inheritance](http://api.rubyonrails.org/classes/ActiveRecord/Base.html)
|
119
|
-
* `(
|
120
|
-
associations.
|
121
|
-
|
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 `Post` class that
|
124
|
+
has many instances of `Comment` will cache the number of existent comments
|
122
125
|
for each post.
|
123
126
|
|
124
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.
|
@@ -126,7 +129,7 @@ NOTE: While these column names are optional, they are in fact reserved by Active
|
|
126
129
|
Creating Active Record Models
|
127
130
|
-----------------------------
|
128
131
|
|
129
|
-
It is very easy to create Active Record models. All you have to do is to
|
132
|
+
It is very easy to create Active Record models. All you have to do is to
|
130
133
|
subclass the `ActiveRecord::Base` class and you're good to go:
|
131
134
|
|
132
135
|
```ruby
|
@@ -134,9 +137,9 @@ class Product < ActiveRecord::Base
|
|
134
137
|
end
|
135
138
|
```
|
136
139
|
|
137
|
-
This will create a `Product` model, mapped to a `products` table at the
|
138
|
-
database. By doing this you'll also have the ability to map the columns of each
|
139
|
-
row in that table with the attributes of the instances of your model. Suppose
|
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
|
140
143
|
that the `products` table was created using an SQL sentence like:
|
141
144
|
|
142
145
|
```sql
|
@@ -147,7 +150,7 @@ CREATE TABLE products (
|
|
147
150
|
);
|
148
151
|
```
|
149
152
|
|
150
|
-
Following the table schema above, you would be able to write code like the
|
153
|
+
Following the table schema above, you would be able to write code like the
|
151
154
|
following:
|
152
155
|
|
153
156
|
```ruby
|
@@ -159,11 +162,11 @@ puts p.name # "Some Book"
|
|
159
162
|
Overriding the Naming Conventions
|
160
163
|
---------------------------------
|
161
164
|
|
162
|
-
What if you need to follow a different naming convention or need to use your
|
163
|
-
Rails application with a legacy database? No problem, you can easily override
|
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
|
164
167
|
the default conventions.
|
165
168
|
|
166
|
-
You can use the `ActiveRecord::Base.table_name=` method to specify the table
|
169
|
+
You can use the `ActiveRecord::Base.table_name=` method to specify the table
|
167
170
|
name that should be used:
|
168
171
|
|
169
172
|
```ruby
|
@@ -172,8 +175,8 @@ class Product < ActiveRecord::Base
|
|
172
175
|
end
|
173
176
|
```
|
174
177
|
|
175
|
-
If you do so, you will have to define manually the class name that is hosting
|
176
|
-
the fixtures (class_name.yml) using the `set_fixture_class` method in your test
|
178
|
+
If you do so, you will have to define manually the class name that is hosting
|
179
|
+
the fixtures (class_name.yml) using the `set_fixture_class` method in your test
|
177
180
|
definition:
|
178
181
|
|
179
182
|
```ruby
|
@@ -184,7 +187,7 @@ class FunnyJoke < ActiveSupport::TestCase
|
|
184
187
|
end
|
185
188
|
```
|
186
189
|
|
187
|
-
It's also possible to override the column that should be used as the table's
|
190
|
+
It's also possible to override the column that should be used as the table's
|
188
191
|
primary key using the `ActiveRecord::Base.set_primary_key` method:
|
189
192
|
|
190
193
|
```ruby
|
@@ -196,17 +199,17 @@ end
|
|
196
199
|
CRUD: Reading and Writing Data
|
197
200
|
------------------------------
|
198
201
|
|
199
|
-
CRUD is an acronym for the four verbs we use to operate on data: **C**reate,
|
200
|
-
**R**ead, **U**pdate and **D**elete. Active Record automatically creates methods
|
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
|
201
204
|
to allow an application to read and manipulate data stored within its tables.
|
202
205
|
|
203
206
|
### Create
|
204
207
|
|
205
|
-
Active Record objects can be created from a hash, a block or have their
|
206
|
-
attributes manually set after creation. The `new` method will return a new
|
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
|
207
210
|
object while `create` will return the object and save it to the database.
|
208
211
|
|
209
|
-
For example, given a model `User` with attributes of `name` and `occupation`,
|
212
|
+
For example, given a model `User` with attributes of `name` and `occupation`,
|
210
213
|
the `create` method call will create and save a new record into the database:
|
211
214
|
|
212
215
|
```ruby
|
@@ -223,7 +226,7 @@ user.occupation = "Code Artist"
|
|
223
226
|
|
224
227
|
A call to `user.save` will commit the record to the database.
|
225
228
|
|
226
|
-
Finally, if a block is provided, both `create` and `new` will yield the new
|
229
|
+
Finally, if a block is provided, both `create` and `new` will yield the new
|
227
230
|
object to that block for initialization:
|
228
231
|
|
229
232
|
```ruby
|
@@ -235,7 +238,7 @@ end
|
|
235
238
|
|
236
239
|
### Read
|
237
240
|
|
238
|
-
Active Record provides a rich API for accessing data within a database. Below
|
241
|
+
Active Record provides a rich API for accessing data within a database. Below
|
239
242
|
are a few examples of different data access methods provided by Active Record.
|
240
243
|
|
241
244
|
```ruby
|
@@ -258,12 +261,12 @@ david = User.find_by_name('David')
|
|
258
261
|
users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC')
|
259
262
|
```
|
260
263
|
|
261
|
-
You can learn more about querying an Active Record model in the [Active Record
|
264
|
+
You can learn more about querying an Active Record model in the [Active Record
|
262
265
|
Query Interface](active_record_querying.html) guide.
|
263
266
|
|
264
267
|
### Update
|
265
268
|
|
266
|
-
Once an Active Record object has been retrieved, its attributes can be modified
|
269
|
+
Once an Active Record object has been retrieved, its attributes can be modified
|
267
270
|
and it can be saved to the database.
|
268
271
|
|
269
272
|
```ruby
|
@@ -272,7 +275,7 @@ user.name = 'Dave'
|
|
272
275
|
user.save
|
273
276
|
```
|
274
277
|
|
275
|
-
A shorthand for this is to use a hash mapping attribute names to the desired
|
278
|
+
A shorthand for this is to use a hash mapping attribute names to the desired
|
276
279
|
value, like so:
|
277
280
|
|
278
281
|
```ruby
|
@@ -280,8 +283,8 @@ user = User.find_by_name('David')
|
|
280
283
|
user.update(name: 'Dave')
|
281
284
|
```
|
282
285
|
|
283
|
-
This is most useful when updating several attributes at once. If, on the other
|
284
|
-
hand, you'd like to update several records in bulk, you may find the
|
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
|
285
288
|
`update_all` class method useful:
|
286
289
|
|
287
290
|
```ruby
|
@@ -290,7 +293,7 @@ User.update_all "max_login_attempts = 3, must_change_password = 'true'"
|
|
290
293
|
|
291
294
|
### Delete
|
292
295
|
|
293
|
-
Likewise, once retrieved an Active Record object can be destroyed which removes
|
296
|
+
Likewise, once retrieved an Active Record object can be destroyed which removes
|
294
297
|
it from the database.
|
295
298
|
|
296
299
|
```ruby
|
@@ -301,46 +304,46 @@ user.destroy
|
|
301
304
|
Validations
|
302
305
|
-----------
|
303
306
|
|
304
|
-
Active Record allows you to validate the state of a model before it gets written
|
305
|
-
into the database. There are several methods that you can use to check your
|
306
|
-
models and validate that an attribute value is not empty, is unique and not
|
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
|
307
310
|
already in the database, follows a specific format and many more.
|
308
311
|
|
309
|
-
Validation is a very important issue to consider when persisting to database, so
|
310
|
-
the methods `create`, `save` and `update` take it into account when
|
311
|
-
running: they return `false` when validation fails and they didn't actually
|
312
|
-
perform any operation on database. All of these have a bang counterpart (that
|
313
|
-
is, `create!`, `save!` and `update!`), which are stricter in that
|
314
|
-
they raise the exception `ActiveRecord::RecordInvalid` if validation fails.
|
312
|
+
Validation is a very important issue to consider when persisting to database, so
|
313
|
+
the methods `create`, `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 database. All of these have a bang counterpart (that
|
316
|
+
is, `create!`, `save!` and `update!`), which are stricter in that
|
317
|
+
they raise the exception `ActiveRecord::RecordInvalid` if validation fails.
|
315
318
|
A quick example to illustrate:
|
316
319
|
|
317
320
|
```ruby
|
318
321
|
class User < ActiveRecord::Base
|
319
|
-
|
322
|
+
validates :name, presence: true
|
320
323
|
end
|
321
324
|
|
322
325
|
User.create # => false
|
323
326
|
User.create! # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
|
324
327
|
```
|
325
328
|
|
326
|
-
You can learn more about validations in the [Active Record Validations
|
329
|
+
You can learn more about validations in the [Active Record Validations
|
327
330
|
guide](active_record_validations.html).
|
328
331
|
|
329
332
|
Callbacks
|
330
333
|
---------
|
331
334
|
|
332
|
-
Active Record callbacks allow you to attach code to certain events in the
|
333
|
-
life-cycle of your models. This enables you to add behavior to your models by
|
334
|
-
transparently executing code when those events occur, like when you create a new
|
335
|
-
record, update it, destroy it and so on. You can learn more about callbacks in
|
335
|
+
Active Record callbacks allow you to attach code to certain events in the
|
336
|
+
life-cycle of your models. This enables you to add behavior to your models by
|
337
|
+
transparently executing code when those events occur, like when you create a new
|
338
|
+
record, update it, destroy it and so on. You can learn more about callbacks in
|
336
339
|
the [Active Record Callbacks guide](active_record_callbacks.html).
|
337
340
|
|
338
341
|
Migrations
|
339
342
|
----------
|
340
343
|
|
341
|
-
Rails provides a domain-specific language for managing a database schema called
|
342
|
-
migrations. Migrations are stored in files which are executed against any
|
343
|
-
database that Active Record support using `rake`. Here's a migration that
|
344
|
+
Rails provides a domain-specific language for managing a database schema called
|
345
|
+
migrations. Migrations are stored in files which are executed against any
|
346
|
+
database that Active Record support using `rake`. Here's a migration that
|
344
347
|
creates a table:
|
345
348
|
|
346
349
|
```ruby
|
@@ -361,10 +364,10 @@ class CreatePublications < ActiveRecord::Migration
|
|
361
364
|
end
|
362
365
|
```
|
363
366
|
|
364
|
-
Rails keeps track of which files have been committed to the database and
|
367
|
+
Rails keeps track of which files have been committed to the database and
|
365
368
|
provides rollback features. To actually create the table, you'd run `rake db:migrate`
|
366
369
|
and to roll it back, `rake db:rollback`.
|
367
370
|
|
368
|
-
Note that the above code is database-agnostic: it will run in MySQL, postgresql,
|
369
|
-
Oracle and others. You can learn more about migrations in the [Active Record
|
371
|
+
Note that the above code is database-agnostic: it will run in MySQL, postgresql,
|
372
|
+
Oracle and others. You can learn more about migrations in the [Active Record
|
370
373
|
Migrations guide](migrations.html)
|
@@ -76,6 +76,7 @@ The methods are:
|
|
76
76
|
* `reorder`
|
77
77
|
* `reverse_order`
|
78
78
|
* `select`
|
79
|
+
* `distinct`
|
79
80
|
* `uniq`
|
80
81
|
* `where`
|
81
82
|
|
@@ -299,7 +300,7 @@ Client.first(2)
|
|
299
300
|
The SQL equivalent of the above is:
|
300
301
|
|
301
302
|
```sql
|
302
|
-
SELECT * FROM clients LIMIT 2
|
303
|
+
SELECT * FROM clients ORDER BY id ASC LIMIT 2
|
303
304
|
```
|
304
305
|
|
305
306
|
#### last
|
@@ -315,7 +316,7 @@ Client.last(2)
|
|
315
316
|
The SQL equivalent of the above is:
|
316
317
|
|
317
318
|
```sql
|
318
|
-
SELECT * FROM clients ORDER
|
319
|
+
SELECT * FROM clients ORDER BY id DESC LIMIT 2
|
319
320
|
```
|
320
321
|
|
321
322
|
### Retrieving Multiple Objects in Batches
|
@@ -505,19 +506,15 @@ This code will generate SQL like this:
|
|
505
506
|
SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
|
506
507
|
```
|
507
508
|
|
508
|
-
### NOT
|
509
|
+
### NOT Conditions
|
509
510
|
|
510
|
-
`NOT
|
511
|
+
`NOT` SQL queries can be built by `where.not`.
|
511
512
|
|
512
513
|
```ruby
|
513
514
|
Post.where.not(author: author)
|
514
|
-
|
515
|
-
Author.where.like(name: 'Nari%')
|
516
|
-
|
517
|
-
Developer.where.not_like(name: 'Tenderl%')
|
518
515
|
```
|
519
516
|
|
520
|
-
In other words,
|
517
|
+
In other words, this query can be generated by calling `where` with no argument, then immediately chain with `not` passing `where` conditions.
|
521
518
|
|
522
519
|
Ordering
|
523
520
|
--------
|
@@ -580,10 +577,10 @@ ActiveModel::MissingAttributeError: missing attribute: <attribute>
|
|
580
577
|
|
581
578
|
Where `<attribute>` is the attribute you asked for. The `id` method will not raise the `ActiveRecord::MissingAttributeError`, so just be careful when working with associations because they need the `id` method to function properly.
|
582
579
|
|
583
|
-
If you would like to only grab a single record per unique value in a certain field, you can use `
|
580
|
+
If you would like to only grab a single record per unique value in a certain field, you can use `distinct`:
|
584
581
|
|
585
582
|
```ruby
|
586
|
-
Client.select(:name).
|
583
|
+
Client.select(:name).distinct
|
587
584
|
```
|
588
585
|
|
589
586
|
This would generate SQL like:
|
@@ -595,10 +592,10 @@ SELECT DISTINCT name FROM clients
|
|
595
592
|
You can also remove the uniqueness constraint:
|
596
593
|
|
597
594
|
```ruby
|
598
|
-
query = Client.select(:name).
|
595
|
+
query = Client.select(:name).distinct
|
599
596
|
# => Returns unique names
|
600
597
|
|
601
|
-
query.
|
598
|
+
query.distinct(false)
|
602
599
|
# => Returns all names, even if there are duplicates
|
603
600
|
```
|
604
601
|
|
@@ -692,6 +689,27 @@ The SQL that would be executed:
|
|
692
689
|
SELECT * FROM posts WHERE id > 10 LIMIT 20
|
693
690
|
```
|
694
691
|
|
692
|
+
### `unscope`
|
693
|
+
|
694
|
+
The `except` method does not work when the relation is merged. For example:
|
695
|
+
|
696
|
+
```ruby
|
697
|
+
Post.comments.except(:order)
|
698
|
+
```
|
699
|
+
|
700
|
+
will still have an order if the order comes from a default scope on Comment. In order to remove all ordering, even from relations which are merged in, use unscope as follows:
|
701
|
+
|
702
|
+
```ruby
|
703
|
+
Post.order('id DESC').limit(20).unscope(:order) = Post.limit(20)
|
704
|
+
Post.order('id DESC').limit(20).unscope(:order, :limit) = Post.all
|
705
|
+
```
|
706
|
+
|
707
|
+
You can additionally unscope specific where clauses. For example:
|
708
|
+
|
709
|
+
```ruby
|
710
|
+
Post.where(:id => 10).limit(1).unscope(:where => :id, :limit).order('id DESC') = Post.order('id DESC')
|
711
|
+
```
|
712
|
+
|
695
713
|
### `only`
|
696
714
|
|
697
715
|
You can also override conditions using the `only` method. For example:
|
@@ -949,7 +967,7 @@ SELECT categories.* FROM categories
|
|
949
967
|
INNER JOIN posts ON posts.category_id = categories.id
|
950
968
|
```
|
951
969
|
|
952
|
-
Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use `Category.joins(:posts).
|
970
|
+
Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use `Category.joins(:posts).uniq`.
|
953
971
|
|
954
972
|
#### Joining Multiple Associations
|
955
973
|
|
@@ -1175,6 +1193,61 @@ Using a class method is the preferred way to accept arguments for scopes. These
|
|
1175
1193
|
category.posts.created_before(time)
|
1176
1194
|
```
|
1177
1195
|
|
1196
|
+
### Merging of scopes
|
1197
|
+
|
1198
|
+
Just like `where` clauses scopes are merged using `AND` conditions.
|
1199
|
+
|
1200
|
+
```ruby
|
1201
|
+
class User < ActiveRecord::Base
|
1202
|
+
scope :active, -> { where state: 'active' }
|
1203
|
+
scope :inactive, -> { where state: 'inactive' }
|
1204
|
+
end
|
1205
|
+
|
1206
|
+
```ruby
|
1207
|
+
User.active.inactive
|
1208
|
+
# => SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'inactive'
|
1209
|
+
```
|
1210
|
+
|
1211
|
+
We can mix and match `scope` and `where` conditions and the final sql
|
1212
|
+
will have all conditions joined with `AND` .
|
1213
|
+
|
1214
|
+
```ruby
|
1215
|
+
User.active.where(state: 'finished')
|
1216
|
+
# => SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'finished'
|
1217
|
+
```
|
1218
|
+
|
1219
|
+
If we do want the `last where clause` to win then `Relation#merge` can
|
1220
|
+
be used .
|
1221
|
+
|
1222
|
+
```ruby
|
1223
|
+
User.active.merge(User.inactive)
|
1224
|
+
# => SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
|
1225
|
+
```
|
1226
|
+
|
1227
|
+
One important caveat is that `default_scope` will be overridden by
|
1228
|
+
`scope` and `where` conditions.
|
1229
|
+
|
1230
|
+
```ruby
|
1231
|
+
class User < ActiveRecord::Base
|
1232
|
+
default_scope { where state: 'pending' }
|
1233
|
+
scope :active, -> { where state: 'active' }
|
1234
|
+
scope :inactive, -> { where state: 'inactive' }
|
1235
|
+
end
|
1236
|
+
|
1237
|
+
User.all
|
1238
|
+
# => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
|
1239
|
+
|
1240
|
+
User.active
|
1241
|
+
# => SELECT "users".* FROM "users" WHERE "users"."state" = 'active'
|
1242
|
+
|
1243
|
+
User.where(state: 'inactive')
|
1244
|
+
# => SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
|
1245
|
+
```
|
1246
|
+
|
1247
|
+
As you can see above the `default_scope` is being overridden by both
|
1248
|
+
`scope` and `where` conditions.
|
1249
|
+
|
1250
|
+
|
1178
1251
|
### Applying a default scope
|
1179
1252
|
|
1180
1253
|
If we wish for a scope to be applied across all queries to the model we can use the
|
@@ -1221,7 +1294,7 @@ recommended that you use the block form of `unscoped`:
|
|
1221
1294
|
|
1222
1295
|
```ruby
|
1223
1296
|
Client.unscoped {
|
1224
|
-
Client.created_before(Time.
|
1297
|
+
Client.created_before(Time.zone.now)
|
1225
1298
|
}
|
1226
1299
|
```
|
1227
1300
|
|
@@ -1362,7 +1435,7 @@ Client.where(active: true).pluck(:id)
|
|
1362
1435
|
# SELECT id FROM clients WHERE active = 1
|
1363
1436
|
# => [1, 2, 3]
|
1364
1437
|
|
1365
|
-
Client.
|
1438
|
+
Client.distinct.pluck(:role)
|
1366
1439
|
# SELECT DISTINCT role FROM clients
|
1367
1440
|
# => ['admin', 'member', 'guest']
|
1368
1441
|
|
@@ -1378,7 +1451,7 @@ Client.select(:id).map { |c| c.id }
|
|
1378
1451
|
# or
|
1379
1452
|
Client.select(:id).map(&:id)
|
1380
1453
|
# or
|
1381
|
-
Client.select(:id).map { |c| [c.id, c.name] }
|
1454
|
+
Client.select(:id, :name).map { |c| [c.id, c.name] }
|
1382
1455
|
```
|
1383
1456
|
|
1384
1457
|
with
|