Deploy apps to servers that you own and control.
Application monitoring that helps developers get it done.
After creating records, how can you update specific values? Let’s jump back into our sandbox and explore that together.
We have our posts table with title and body columns, and I’ve set up our Post model with a validation and a callback. I’ve also created an initial post with title: "title one" and "some text" for the body. Now, let’s clear everything and start working with updates.
The most common way to update a particular value is by calling the update! method, passing the column name and a new value:
post.update!(title: "updated")
This method:
Examining the SQL query, we see:
UPDATE posts SET title = ?, updated_at = ? WHERE posts.id = ?
This ensures that every update follows the same structure, improving performance and preventing SQL injection.
If we try to update the title to an empty value, our validation rule kicks in:
post.update!(title: nil)
# => ActiveRecord::RecordInvalid: Validation failed: Title can't be blank
Using update without the bang (!), we get false instead of an exception:
post.update(title: nil)
# => false
post.errors
# => [...Error attribute=title, type=blank,...]
This allows us to choose how to handle errors—whether to catch them explicitly with update! or check them manually with update.
What if we need to update a record without triggering validations or callbacks? We can use update_columns:
post.update_columns(title: nil)
Key differences:
Checking the database:
post.reload.title
# => nil (Title is now empty, even though validations would normally prevent this)
Because update_columns skips important Rails mechanisms, use it carefully—only when you’re sure it’s necessary.
Much like new, you can also update an attribute directly on a post instance and call save:
post.title = "updated again"
post.save!
Using save! ensures an exception is raised on failure, while save returns false if the update is invalid:
post.title = nil
post.save
# => false
post.errors.full_messages
# => [...Error attribute=title, type=blank,...]
Method | Runs Validations? | Runs Callbacks? | Updates updated_at? | Best Use Case |
---|---|---|---|---|
update! | ✅ Yes | ✅ Yes | ✅ Yes | Default method for updates |
update | ✅ Yes | ✅ Yes | ✅ Yes | When you want to check errors manually |
update_columns | ❌ No | ❌ No | ❌ No | Skipping validations and callbacks for performance-sensitive updates |
save! | ✅ Yes | ✅ Yes | ✅ Yes | Ensures an exception on failure |
save | ✅ Yes | ✅ Yes | ✅ Yes | When updating an instance directly |
In the next video, we’ll explore a more advanced technique—updating or inserting records in a single SQL query for even greater efficiency.