The blog has moved to http://jessehouse.com/ ... Many google searches point here so I am leaving it operational, but there will be no new posts.

Wednesday, August 18, 2010

valid? vs errors.any? in rails

Recently got bit by checking valid? in some rails code, thought I would share.

In this situation I was manually adding to the errors collection of an ActiveRecord object and then calling valid? to see if the object was ok; this is not the normal style of validation on ActiveRecord objects, if I had been playing by the rules valid? would have done what I needed; it would check the current state of my objects attributes and 're-validate' the object.

This screen shot of an irb console session shows the issue I was running into


valid-v-errors-any

Taking a look at the source code for valid? it becomes obvious why the manually added errors get cleared, just not what I expected to happen


valid-source