Clear Active Record Error in Rails 3.1

I upgrade the application from Rails 3.0 to 3.1 and find the following error message:

NoMethodError: undefined method `delete' for #<ActiveModel::Errors:0x007f928c0ee310> 

I have the following snippet that moves errors:

 after_validation do self.errors[:image_size].each do |message| self.errors.add(:image, message) end self.errors[:image_extension].each do |message| self.errors.add(:image, message) end self.errors.delete(:image_size) self.errors.delete(:image_extension) end 

I still need to migrate all the checks from image_size and image_extension , but I'm not sure how to do this in Rails 3.1. Any ideas?

+4
source share
2 answers

The only method that removes anything is clear , and removes everything, so I think you need:

  • Retrieve all error messages (possibly using to_hash ).
  • Clear all errors with self.errors.clear .
  • Put all error messages in the right / right places using self.errors.add .
+7
source

You can directly change the attribute of the hash-like messages of the errors object, i.e. you can do this:

 self.errors.messages.delete(:image_size) 

This does not appear in the documentation, but looking at the actual code for ActiveModel::Errors , we find the attr_reader defined for @messages:

 attr_reader :messages 

so it seems that direct access to it should be an acceptable use

+5
source

All Articles