Skip to content

Instantly share code, notes, and snippets.

@jcf
Created September 17, 2009 10:52
Show Gist options
  • Save jcf/188447 to your computer and use it in GitHub Desktop.
Save jcf/188447 to your computer and use it in GitHub Desktop.
Copy errors on an ActiveRecord object in to another instance's errors
# cat, dog = Cat.new, Dog.new
# cat.friends << dog
# cat.save
# => false
# cat.errors
# #<ActiveRecord::Errors ... @errors={"dog" => "is not valid"}>
# cat.errors << dog.errors
# cat.errors
# #<ActiveRecord::Errors ... @errors={"dog" => "is not valid", "bark" => "is not bigger than bite"}
class ActiveRecord::Errors
def <<(other_errors)
@errors.merge!(other_errors.instance_variable_get(:@errors))
end
end
@qbantek
Copy link

qbantek commented Aug 30, 2020

copy!(other) public
Copies the errors from other.

other - The ActiveModel::Errors instance.

Examples

person.errors.copy!(other)

source: https://apidock.com/rails/v5.2.3/ActiveModel/Errors/copy%21

@montulli
Copy link

Clarification. Use the errors from the 'other' object as the argument:

person.errors.copy!(other_object.errors)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment