Article.find(id): look up by primary key

Free preview 1 min to read

The line from the first ActiveRecord lesson

article = Article.find(1)
article.title
# => "Hello Rails"

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.

A saved row, found by its id

article = ScratchArticle.create!(title: "Hello Rails")
ScratchArticle.find(article.id).title
# => "Hello Rails"

Checked against a throwaway table: the id that .create! assigns is the value .find needs to get the row back. It's the same id you saw appear on save in the previous course.

A lookup by id

.find expects one id, not a description of what to look for. It matches the primary key, the id column. Looking up by anything else, like a title or slug, starts in the next lesson.

Key takeaways

  • Article.find(1) looks up a row by its primary key, id.
  • The id assigned on save is the value .find uses to get that row back.
  • .find looks up by id only; other attributes come next.
Lesson 1 of 7 · free

Keep going with lesson 2

find raises when nothing matches

find raises ActiveRecord::RecordNotFound for a missing id, and in production Rails answers that with a 404.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...