Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fixed custom validation context bug where child

associations were not being saved.

Fixes #13854.

[Eric Chahin, Aaron Nelson, & Kevin Casey]
  • Loading branch information...
commit c6d685ba1118cc1f6303122117df945ebe8fceae 1 parent 8761557
@eric-chahin eric-chahin authored
View
7 activerecord/CHANGELOG.md
@@ -1,3 +1,10 @@
+* Rails will now pass a custom validation context through to autosave associations
+ in order to validate child associations with the same context.
+
+ Fixes #13854.
+
+ *Eric Chahin*, *Aaron Nelson*, *Kevin Casey*
+
* When using a custom `join_table` name on a `habtm`, rails was not saving it
on Reflections. This causes a problem when rails loads fixtures, because it
uses the reflections to set database with fixtures.
View
3  activerecord/lib/active_record/autosave_association.rb
@@ -304,7 +304,8 @@ def validate_collection_association(reflection)
def association_valid?(reflection, record)
return true if record.destroyed? || record.marked_for_destruction?
- unless valid = record.valid?
+ validation_context = self.validation_context unless [:create,:update].include?(self.validation_context)
+ unless valid = record.valid?(validation_context)
if reflection.options[:autosave]
record.errors.each do |attribute, message|
attribute = "#{reflection.name}.#{attribute}"
View
10 activerecord/test/cases/associations/has_many_associations_test.rb
@@ -26,6 +26,8 @@
require 'models/job'
require 'models/college'
require 'models/student'
+require 'models/pirate'
+require 'models/ship'
class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase
fixtures :authors, :posts, :comments
@@ -1877,4 +1879,12 @@ def test_collection_association_with_private_kernel_method
end
end
end
+
+ test 'has_many_association passes context validation to validate children' do
+ pirate = FamousPirate.new
+ pirate.famous_ships << ship = FamousShip.new
+ assert_equal true, pirate.valid?
+ assert_equal false, pirate.valid?(:conference)
+ assert_equal "can't be blank", ship.errors[:name].first
+ end
end
View
6 activerecord/test/models/pirate.rb
@@ -84,3 +84,9 @@ def log(record, callback)
class DestructivePirate < Pirate
has_one :dependent_ship, :class_name => 'Ship', :foreign_key => :pirate_id, :dependent => :destroy
end
+
+class FamousPirate < ActiveRecord::Base
+ self.table_name = 'pirates'
+ has_many :famous_ships
+ validates_presence_of :catchphrase, on: :conference
+end
View
6 activerecord/test/models/ship.rb
@@ -17,3 +17,9 @@ def cancel_save_callback_method
false
end
end
+
+class FamousShip < ActiveRecord::Base
+ self.table_name = 'ships'
+ belongs_to :famous_pirate
+ validates_presence_of :name, on: :conference
+end
Please sign in to comment.
Something went wrong with that request. Please try again.