.new builds, .create persists
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
.newonly builds an in-memory instance:persisted?isfalseandidisnil..createbuilds and saves in one call:persisted?istrueand anidis assigned..createis a shortcut for.newthen.save.- The next lesson covers
.saveon its own.
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.