I'm learning RoR at the moment, and I think I must be misunderstanding something.
I have an ActiveRecord class call User, with simple validations on :name and :email such as presence: true, length: { maximum: 15 }, etc. I thought I'd check the validations in the console. I go into rails console (development env), and create a new instance with a name that is too long, such as user_instance = User.new (name:"aaaaabbbbbcccccddddd", email:"").
The validation doesn't throw up any errors. When I try user_instance.save, the record won't write to the DB, so it's obviously working fine at that stage. What am I doing wrong?
When you want to get an exception raised on record saving, use save!
instead of save
(same with update
/update!
, create/create!
).
With save
you won't have an exception raised if there are validation errors, it will just return false
. You can also check if there are errors on an instance with user_instance.valid?
and get the errors with user_instance.errors
.
See When Does Validation Happen?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With