aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorDmitry Polushkin <dmitry.polushkin@gmail.com>2015-09-07 22:41:50 +0100
committerDmitry Polushkin <dmitry.polushkin@gmail.com>2015-09-07 22:42:50 +0100
commite3d99e239dd1b59d31ac90f74186ded8b55de599 (patch)
treee0ce0816d764133343f1b5bbf6e19efd6bbb1c63 /activerecord
parentd1ce45cd8c77bea3c5b7d197a66f172ffcd5e6a6 (diff)
downloadrails-e3d99e239dd1b59d31ac90f74186ded8b55de599.tar.gz
rails-e3d99e239dd1b59d31ac90f74186ded8b55de599.tar.bz2
rails-e3d99e239dd1b59d31ac90f74186ded8b55de599.zip
Validate multiple contexts on `valid?` and `invalid?` at once.
Example: ```ruby class Person include ActiveModel::Validations attr_reader :name, :title validates_presence_of :name, on: :create validates_presence_of :title, on: :update end person = Person.new person.valid?([:create, :update]) # => true person.errors.messages # => {:name=>["can't be blank"], :title=>["can't be blank"]} ```
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/lib/active_record/validations.rb6
-rw-r--r--activerecord/test/cases/validations_test.rb7
2 files changed, 12 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index 34d96b19fe..e6b4120c5d 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -54,7 +54,7 @@ module ActiveRecord
# 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 valid?(context = nil)
- context ||= (new_record? ? :create : :update)
+ context ||= default_validation_context
output = super(context)
errors.empty? && output
end
@@ -63,6 +63,10 @@ module ActiveRecord
protected
+ def default_validation_context
+ new_record? ? :create : :update
+ end
+
def raise_validation_error
raise(RecordInvalid.new(self))
end
diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb
index f4f316f393..a429d06aad 100644
--- a/activerecord/test/cases/validations_test.rb
+++ b/activerecord/test/cases/validations_test.rb
@@ -52,6 +52,13 @@ class ValidationsTest < ActiveRecord::TestCase
assert r.valid?(:special_case)
end
+ def test_invalid_using_multiple_contexts
+ r = WrongReply.new(:title => 'Wrong Create')
+ assert r.invalid?([:special_case, :create])
+ assert_equal "Invalid", r.errors[:author_name].join
+ assert_equal "is Wrong Create", r.errors[:title].join
+ end
+
def test_validate
r = WrongReply.new