From 86e314fd25172737d518ce1853002f0f2c64e632 Mon Sep 17 00:00:00 2001 From: maniSHarma7575 Date: Fri, 12 Jul 2024 10:22:12 +0530 Subject: [PATCH] [DOC] Update Active Record basic guide for create method in case of validation fails --- guides/source/active_record_basics.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md index 7e370f7208024..48b0e375af93b 100644 --- a/guides/source/active_record_basics.md +++ b/guides/source/active_record_basics.md @@ -586,8 +586,10 @@ unique, is not already in the database, follows a specific format, and many more. Methods like `save`, `create` and `update` validate a model before persisting it -to the database. When a model is invalid these methods return `false` and no -database operations are performed. All of these methods have a bang counterpart +to the database. If the model is invalid, no database operations are performed. In +this case the `save` and `update` methods return `false`. The +`create` method still returns the ActiveRecord object, which can be checked for +errors. All of these methods have a bang counterpart (that is, `save!`, `create!` and `update!`), which are stricter in that they raise an `ActiveRecord::RecordInvalid` exception when validation fails. A quick example to illustrate: @@ -606,6 +608,16 @@ irb> user.save! ActiveRecord::RecordInvalid: Validation failed: Name can't be blank ``` +The `create` method in the example returns an ActiveRecord object, regardless of +its validity. You can then inspect this object for any errors. + +```irb +irb> user = User.create +=> # +irb> user.errors.full_messages +=> ["Name can't be blank"] +``` + You can learn more about validations in the [Active Record Validations guide](active_record_validations.html).