ActiveRecord: finding records
This course covers three ways ActiveRecord finds rows in a table. Article.find looks up a row by its primary key and raises ActiveRecord::RecordNotFound when no row matches. find_by looks up by any attribute and returns nil on a miss. Article.all returns an ActiveRecord::Relation, which supports each, map and select and runs no SQL until something needs the rows. The lessons also check each lookup in the console sandbox and end with an example that combines all three methods.
What you'll learn
- ✓Looking up a row by its primary key with find
- ✓How find raises ActiveRecord::RecordNotFound for a missing id
- ✓Looking up by any attribute with find_by, which returns nil on a miss
- ✓What an ActiveRecord::Relation is and how it supports Enumerable methods
- ✓Why a relation runs no query until its rows are needed
- ✓Checking lookups in the console sandbox
Article.find(id): look up by primary key
ActiveRecord: model introduction opened on this line without explaining it. Article.find(1) looks up the row whose id is 1 and returns the matching instance, already built, like those ActiveRecord: creating records produced with .save.
Read the full lesson free →Curriculum
7 lessonsArticle.find(id): look up by primary key
Article.find looks up a row by its primary key, the id assigned when the record is saved.
find raises when nothing matches
find raises ActiveRecord::RecordNotFound for a missing id, and in production Rails answers that with a 404.
find_by: the same idea, without the crash
find_by looks up by any attribute and returns nil when nothing matches, with no exception raised.
Article.all: every row, as a relation
Article.all returns an ActiveRecord::Relation, which supports each, map, select and the rest of Enumerable.
A query waits until it's actually needed
Building a relation runs no SQL, and the query runs once something enumerates or converts it.
Every lookup, confirmed live
The console sandbox runs each lookup on a demo row and rolls that row back on exit.
Putting it together: locate, then decide
A recap of when to use find, find_by or all, and how each one handles a miss.