ActiveRecord: creating records
This course covers how ActiveRecord creates database rows. It compares .new, which builds an instance in memory, with .create, which builds and saves in one call. It explains .save and its true or false return value, what happens when validation fails, and how errors.full_messages reports the failed rule. It shows when save! and create! should raise ActiveRecord::RecordInvalid. It also names mass assignment, explains why controllers avoid raw params, and shows how to try every method in a console sandbox.
What you'll learn
- ✓The difference between .new and .create
- ✓How .save persists a built instance and returns a boolean
- ✓Reading errors.full_messages after a failed save
- ✓When to use save! and create! to raise on failure
- ✓What mass assignment is and why raw params need a safeguard
- ✓Trying write methods safely in rails console --sandbox
.new builds, .create persists
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.
Read the full lesson free →Curriculum
7 lessons.new builds, .create persists
Compares .new, which builds an unsaved instance, with .create, which builds and saves it in one call.
.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.
When save returns false
Explains how a failed validation makes .save return false and how errors.full_messages names the failed rule.
save! and create!: when failure should raise
Covers save! and create!, which raise ActiveRecord::RecordInvalid, and when to prefer them over the plain versions.
A hash of attributes, handled carefully
Names mass assignment and explains why a controller passes article_params to .new instead of raw params.
Trying all of this in a sandbox
Runs every write method from the course inside a console sandbox, where exit rolls back each change.
Putting it together: one save, every path
Reviews building, saving, failing, raising, safe mass assignment and sandbox testing through a single two-line example.