aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib
diff options
context:
space:
mode:
authorBogdan Gusiev <agresso@gmail.com>2014-06-23 16:09:40 +0300
committerBogdan Gusiev <agresso@gmail.com>2014-06-23 16:11:06 +0300
commit0fa4c95d914d9f04553642f5181ee7c2cf4c6add (patch)
tree71a6c96eadab070dee60724fc289b0e883f23bca /activerecord/lib
parent8a6b8c8a7991796ae961db2be0b0f683a1c1efc6 (diff)
downloadrails-0fa4c95d914d9f04553642f5181ee7c2cf4c6add.tar.gz
rails-0fa4c95d914d9f04553642f5181ee7c2cf4c6add.tar.bz2
rails-0fa4c95d914d9f04553642f5181ee7c2cf4c6add.zip
Add AR::Base#validate! method
Acts same as valid? but raises AR::RecordInvalid exception if validation fails
Diffstat (limited to 'activerecord/lib')
-rw-r--r--activerecord/lib/active_record/validations.rb18
1 files changed, 17 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index 9999624fcf..b4b33804de 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -54,7 +54,7 @@ module ActiveRecord
# Attempts to save the record just like Base#save but will raise a +RecordInvalid+
# exception instead of returning +false+ if the record is not valid.
def save!(options={})
- perform_validations(options) ? super : raise(RecordInvalid.new(self))
+ perform_validations(options) ? super : raise_record_invalid
end
# Runs all the validations within the specified context. Returns +true+ if
@@ -75,8 +75,24 @@ module ActiveRecord
alias_method :validate, :valid?
+ # Runs all the validations within the specified context. Returns +true+ if
+ # no errors are found, raises +RecordInvalid+ otherwise.
+ #
+ # If the argument is +false+ (default is +nil+), the context is set to <tt>:create</tt> if
+ # <tt>new_record?</tt> is +true+, and to <tt>:update</tt> if it is not.
+ #
+ # Validations with no <tt>:on</tt> option will run no matter the context. Validations with
+ # some <tt>:on</tt> option will only run in the specified context.
+ def validate!(context = nil)
+ valid?(context) || raise_record_invalid
+ end
+
protected
+ def raise_record_invalid
+ raise(RecordInvalid.new(self))
+ end
+
def perform_validations(options={}) # :nodoc:
options[:validate] == false || valid?(options[:context])
end