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

I am learning RoR at the moment, and I think I should misunderstand something.

I have a call to the ActiveRecord User class with simple checks on: name and: email, for example, the presence of: true, length: {maximum: 15}, etc. I thought I would check the checks in the console. I go to the rails (development env) console and create a new instance with a name that is too long, for example user_instance = User.new (name: "aaaaabbbbbcccccddddd", email: "").

Verification does not cause errors. When I try user_instance.save, the record will not be written to the database, so at this point it obviously works fine. What am I doing wrong?

+6
source share
2 answers

If you want to get an exception raised when saving a record, use save! instead of save (same with update / update! create/create! ).

With save , you will not have an exception, if there are validation errors, it will simply return false . You can also check if there are errors in the instance with user_instance.valid? and get errors using user_instance.errors .

See When does verification take place? .

+13
source

the check will not lead to errors if you try to install invalid data on your model, but the save will not be performed.

if you want to check that the validation works, just check user.valid? and it should return false

after calling valid? , you can check user.errors for specific errors set on your model.

+5
source

Source: https://habr.com/ru/post/908178/


All Articles