diff options
author | Tony Jian <tonytonyjan@gmail.com> | 2014-07-21 16:48:37 +0800 |
---|---|---|
committer | Tony Jian <tonytonyjan@gmail.com> | 2014-07-23 16:31:55 +0800 |
commit | d0af90592540225080d03ea2384da759f18620ff (patch) | |
tree | 04eca5bc3fef3aeea5ac41082d5c78903fd40d8d | |
parent | 08754f12e65a9ec79633a605e986d0f1ffa4b251 (diff) | |
download | rails-d0af90592540225080d03ea2384da759f18620ff.tar.gz rails-d0af90592540225080d03ea2384da759f18620ff.tar.bz2 rails-d0af90592540225080d03ea2384da759f18620ff.zip |
`create` return an active record object with erros instead of false when validation fails. [skip ci]
-rw-r--r-- | guides/source/active_record_basics.md | 9 |
1 files changed, 5 insertions, 4 deletions
diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md index 21022f1abb..eff93ce41d 100644 --- a/guides/source/active_record_basics.md +++ b/guides/source/active_record_basics.md @@ -310,10 +310,10 @@ models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format and many more. Validation is a very important issue to consider when persisting to the database, so -the methods `create`, `save` and `update` take it into account when +the methods `save` and `update` take it into account when running: they return `false` when validation fails and they didn't actually perform any operation on the database. All of these have a bang counterpart (that -is, `create!`, `save!` and `update!`), which are stricter in that +is, `save!` and `update!`), which are stricter in that they raise the exception `ActiveRecord::RecordInvalid` if validation fails. A quick example to illustrate: @@ -322,8 +322,9 @@ class User < ActiveRecord::Base validates :name, presence: true end -User.create # => false -User.create! # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank +user = User.new +user.save # => false +user.save! # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank ``` You can learn more about validations in the [Active Record Validations |