diff options
author | Jon Moss <maclover7@users.noreply.github.com> | 2016-01-18 10:31:39 -0500 |
---|---|---|
committer | Jon Moss <maclover7@users.noreply.github.com> | 2016-01-18 10:31:39 -0500 |
commit | 5f302eabae3dfd09ad9d0b5ed285c2973a39a4e3 (patch) | |
tree | 71daf82842da5805294ec60e97591b294ca241ef /guides/source | |
parent | eb2c0e23f9453b18e66e17668927705e1ed22f68 (diff) | |
parent | c70c42891e316dc2370ac5d532d5ad151ca169e1 (diff) | |
download | rails-5f302eabae3dfd09ad9d0b5ed285c2973a39a4e3.tar.gz rails-5f302eabae3dfd09ad9d0b5ed285c2973a39a4e3.tar.bz2 rails-5f302eabae3dfd09ad9d0b5ed285c2973a39a4e3.zip |
Merge pull request #22705 from RochesterinNYC/add-order-explanation-to-first-last-guides
Add clarification about `first` and `last` behavior when using `order` [ci skip]
Diffstat (limited to 'guides/source')
-rw-r--r-- | guides/source/active_record_querying.md | 30 |
1 files changed, 28 insertions, 2 deletions
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index fd5399baec..674f498ae4 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -170,7 +170,7 @@ TIP: The retrieved record may vary depending on the database engine. #### `first` -The `first` method finds the first record ordered by the primary key. For example: +The `first` method finds the first record ordered by primary key (default). For example: ```ruby client = Client.first @@ -204,11 +204,24 @@ The SQL equivalent of the above is: SELECT * FROM clients ORDER BY clients.id ASC LIMIT 3 ``` +On a collection that is ordered using `order`, `first` will return the first record ordered by the specified attribute for `order`. + +```ruby +client = Client.order(:first_name).first +# => #<Client id: 2, first_name: "Fifo"> +``` + +The SQL equivalent of the above is: + +```sql +SELECT * FROM clients ORDER BY clients.first_name ASC LIMIT 1 +``` + The `first!` method behaves exactly like `first`, except that it will raise `ActiveRecord::RecordNotFound` if no matching record is found. #### `last` -The `last` method finds the last record ordered by the primary key. For example: +The `last` method finds the last record ordered by primary key (default). For example: ```ruby client = Client.last @@ -242,6 +255,19 @@ The SQL equivalent of the above is: SELECT * FROM clients ORDER BY clients.id DESC LIMIT 3 ``` +On a collection that is ordered using `order`, `last` will return the last record ordered by the specified attribute for `order`. + +```ruby +client = Client.order(:first_name).last +# => #<Client id: 220, first_name: "Sara"> +``` + +The SQL equivalent of the above is: + +```sql +SELECT * FROM clients ORDER BY clients.first_name DESC LIMIT 1 +``` + The `last!` method behaves exactly like `last`, except that it will raise `ActiveRecord::RecordNotFound` if no matching record is found. #### `find_by` |