开发者

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:

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 st开发者_高级运维ill 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. Any ideas?


The only method that removes anything is clear and the removes everything so I think you have to:

  • Pull all the error messages out (probably using to_hash).
  • Clear all the errors with self.errors.clear.
  • Put all the error messages back in the right/desired places using self.errors.add.


You can directly modify the hash-like messages attribute of the errors object, that is you can do this:

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:

attr_reader :messages

so it looks like that directly accessing it should be acceptable use

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜