aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2005-01-15 17:52:08 +0000
committerDavid Heinemeier Hansson <david@loudthinking.com>2005-01-15 17:52:08 +0000
commit51390b8524a644aa8655691fc7bf56e2a174d140 (patch)
tree5e982bec1cfe5b730930f0996a4330fbc652f0d9 /activerecord/lib
parent823554eafef9e8ee8fe2788f6231a3e665c2cbbf (diff)
downloadrails-51390b8524a644aa8655691fc7bf56e2a174d140.tar.gz
rails-51390b8524a644aa8655691fc7bf56e2a174d140.tar.bz2
rails-51390b8524a644aa8655691fc7bf56e2a174d140.zip
Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@418 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activerecord/lib')
-rwxr-xr-xactiverecord/lib/active_record/validations.rb33
1 files changed, 33 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index 1da73d6dc5..d4f75052d3 100755
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -271,6 +271,39 @@ module ActiveRecord
end
end
end
+
+ # Validates whether the associated object or objects are all themselves valid. Works with any kind of assocation.
+ #
+ # class Book < ActiveRecord::Base
+ # has_many :pages
+ # belongs_to :library
+ #
+ # validates_associated :pages, :library
+ # end
+ #
+ # Warning: If, after the above definition, you then wrote:
+ #
+ # class Page < ActiveRecord::Base
+ # belongs_to :book
+ #
+ # validates_associated :book
+ # end
+ #
+ # this would specify a circular dependency and cause infinite recursion. The Rails team recommends against this practice.
+ #
+ # Configuration options:
+ # * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
+ def validates_associated(*attr_names)
+ configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save }
+ configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
+
+ for attr_name in attr_names
+ class_eval(%(#{validation_method(configuration[:on])} %{
+ errors.add("#{attr_name}", "#{configuration[:message]}") unless
+ (#{attr_name}.is_a?(Array) ? #{attr_name} : [#{attr_name}]).inject(true){ |memo, record| memo and (record.nil? or record.valid?) }
+ }))
+ end
+ end
private