Article.find(id): look up by primary key
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
idassigned on save is the value.finduses to get that row back. .findlooks up byidonly; other attributes come next.
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.