提交 5f8274ef 编写于 作者: J José Valim

Merge pull request #4490 from EmmanuelOga/master

when validating a record, if a validation context is used, use the same context when validating related records 
...@@ -295,7 +295,7 @@ def validate_collection_association(reflection) ...@@ -295,7 +295,7 @@ def validate_collection_association(reflection)
def association_valid?(reflection, record) def association_valid?(reflection, record)
return true if record.destroyed? || record.marked_for_destruction? return true if record.destroyed? || record.marked_for_destruction?
unless valid = record.valid? unless valid = record.valid?(validation_context)
if reflection.options[:autosave] if reflection.options[:autosave]
record.errors.each do |attribute, message| record.errors.each do |attribute, message|
attribute = "#{reflection.name}.#{attribute}" attribute = "#{reflection.name}.#{attribute}"
......
...@@ -2,7 +2,7 @@ module ActiveRecord ...@@ -2,7 +2,7 @@ module ActiveRecord
module Validations module Validations
class AssociatedValidator < ActiveModel::EachValidator class AssociatedValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value) def validate_each(record, attribute, value)
if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?}.any? if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?(record.validation_context) }.any?
record.errors.add(attribute, :invalid, options.merge(:value => value)) record.errors.add(attribute, :invalid, options.merge(:value => value))
end end
end end
......
...@@ -118,4 +118,21 @@ def test_validates_presence_of_belongs_to_association__existing_parent ...@@ -118,4 +118,21 @@ def test_validates_presence_of_belongs_to_association__existing_parent
end end
end end
def test_validates_associated_models_in_the_same_context
Topic.validates_presence_of :title, :on => :custom_context
Topic.validates_associated :replies
Reply.validates_presence_of :title, :on => :custom_context
t = Topic.new('title' => '')
r = t.replies.new('title' => '')
assert t.valid?
assert !t.valid?(:custom_context)
t.title = "Longer"
assert !t.valid?(:custom_context), "Should NOT be valid if the associated object is not valid in the same context."
r.title = "Longer"
assert t.valid?(:custom_context), "Should be valid if the associated object is not valid in the same context."
end
end end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册