diff options
author | James Wen <jrw2175@columbia.edu> | 2015-12-20 03:34:00 -0500 |
---|---|---|
committer | James Wen <jrw2175@columbia.edu> | 2015-12-20 03:34:00 -0500 |
commit | c70c42891e316dc2370ac5d532d5ad151ca169e1 (patch) | |
tree | cb21e20b870326fa641966381d64e2d10cb8d81c /guides | |
parent | cf8621a3e9676f0c62d84dc42797e75bc6ab1a1d (diff) | |
download | rails-c70c42891e316dc2370ac5d532d5ad151ca169e1.tar.gz rails-c70c42891e316dc2370ac5d532d5ad151ca169e1.tar.bz2 rails-c70c42891e316dc2370ac5d532d5ad151ca169e1.zip |
Add clarification about `first` and `last` behavior when using `order` [ci skip]
Diffstat (limited to 'guides')
-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 4606ac4683..1bee89ea4b 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` |