Intern Track Roadmap

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
Free preview · Lesson 1 1 min read

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 lessons
Type to start searching...