From e3d99e239dd1b59d31ac90f74186ded8b55de599 Mon Sep 17 00:00:00 2001 From: Dmitry Polushkin Date: Mon, 7 Sep 2015 22:41:50 +0100 Subject: 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"]} ``` --- activerecord/lib/active_record/validations.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'activerecord/lib') 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 :on option will run no matter the context. Validations with # some :on 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 -- cgit v1.2.3