[英]Remove Active Record Error in Rails 3.1
I'm upgrading an application from Rails 3.0 to 3.1 and found the following error showing up in my tests: 我正在将应用程序从Rails 3.0升级到3.1,并在我的测试中发现以下错误:
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 be able to move all validations from image_size
and image_extension
, but I'm not sure how do this in Rails 3.1. 我仍然需要能够从image_size
和image_extension
移动所有验证,但我不知道在Rails 3.1中如何做到这一点。 Any ideas? 有任何想法吗?
The only method that removes anything is clear
and the removes everything so I think you have to: 删除任何东西的唯一方法是clear
,删除所有内容,所以我认为你必须:
to_hash
). 拉出所有错误消息(可能使用to_hash
)。 self.errors.clear
. 使用self.errors.clear
清除所有错误。 self.errors.add
. 使用self.errors.add
将所有错误消息放回正确/所需的位置。 You can directly modify the hash-like messages attribute of the errors object, that is you can do this: 您可以直接修改errors对象的类似hash的消息属性,即可以执行以下操作:
self.errors.messages.delete(:image_size)
This is not exposed in the documentation, but looking at the actual code for ActiveModel::Errors
we find an attr_reader defined for @messages: 这没有在文档中公开,但是查看ActiveModel::Errors
的实际代码,我们找到为@messages定义的attr_reader:
attr_reader :messages
so it looks like that directly accessing it should be acceptable use 所以看起来直接访问它应该是可接受的用途
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.