Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I check ActiveRecord validations in the console?

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?

like image 245
micklec Avatar asked Feb 10 '12 20:02

micklec


1 Answers

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?.

like image 55
Florent2 Avatar answered Sep 28 '22 00:09

Florent2