Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

when validating a record, if a validation context is used, use the same context when validating related records #4490

Merged
merged 1 commit into from
Jan 17, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/autosave_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ def validate_collection_association(reflection)
def association_valid?(reflection, record)
return true if record.destroyed? || record.marked_for_destruction?

unless valid = record.valid?
unless valid = record.valid?(validation_context)
if reflection.options[:autosave]
record.errors.each do |attribute, message|
attribute = "#{reflection.name}.#{attribute}"
Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/validations/associated.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module ActiveRecord
module Validations
class AssociatedValidator < ActiveModel::EachValidator
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))
end
end
Expand Down
17 changes: 17 additions & 0 deletions activerecord/test/cases/validations/association_validation_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,21 @@ def test_validates_presence_of_belongs_to_association__existing_parent
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