.new builds, .create persists

Free preview 1 min to read

Two calls that look alike

article = Article.new(title: "Hello Rails")
article.persisted?
# => false
article.id
# => nil

ActiveRecord: model introduction built instances this way. .new never touches the database: persisted? returns false, and id stays nil because no row was assigned one.

article = Article.create(title: "Created Directly")
article.persisted?
# => true
article.id
# => 1

.create looks almost the same, with the same class and attribute hash, but the result differs: a saved row, an assigned id, and persisted? returning true. Building the instance and saving it in one call is all .create does.

Two steps, compressed into one

.create is .new followed by .save, the method lesson 2 covers, not a separate mechanism. Use it when nothing needs to happen to the instance between building and saving.

Key takeaways

  • .new only builds an in-memory instance: persisted? is false and id is nil.
  • .create builds and saves in one call: persisted? is true and an id is assigned.
  • .create is a shortcut for .new then .save.
  • The next lesson covers .save on its own.
Lesson 1 of 7 · free

Keep going with lesson 2

.save: turning a built instance into a real row

Shows how .save turns a built instance into a row and returns true or false instead of the record.

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

Type to start searching...