Application monitoring that helps developers get it done.
Deploy apps to servers that you own and control.
In our last video, we learned how to use Active Record’s create and save commands to insert records into our tables. We saw how these generate generic SQL queries, wrap them in transactions to ensure data integrity, and provide error-handling mechanisms using the exclamation point (!) or its absence.
In this video, I want to explore how Active Record handles errors, what actually happens behind the scenes, and how we can control these behaviors.
Jumping into our IRB playground session, I’ve added more details to our Post model:
Let’s get this set up and explore edge cases in how create and save handle errors.
Instead of supplying values, let’s try creating an empty record:
post = Post.create!
This raises an exception with a long stack trace with a validation error:
Validation failed: Title can't be blank (ActiveRecord::RecordInvalid)
We also notice that no SQL queries are executed. This confirms that Active Record stops execution if validations fail, preventing invalid data from reaching the database.
Now, let’s try creating a record without the exclamation point:
post = Post.create
Again, no SQL queries are executed, but this time, instead of raising an exception, we get back a blank Post object.
Checking post.errors reveals:
post.errors
# => [#<ActiveModel::Error attribute=title, type=blank, options={}]>
With both the create and save method, it is always going to first run the validations defined on the Active Record Model.
If a record fails validation, it is halted and no SQL queries are executed. Instead either the bang (!) version raises an exception or the non-bang version returns a non-persisted object with validation errors.
In summary, you can:
So far, we haven’t seen our callback message print. That’s because the record hasn’t been created successfully.
Now, let’s create a valid record:
Post.create!(title: "new title")
This time, we see:
In the next video, we’ll explore how to insert records directly into the database without triggering validations or callbacks—a technique that can be useful for performance-sensitive operations.