validates_presence_of saves NULL as valid
âModel w/string :url, validates_presence_of :url but saves NULL as valid, then wonât update via any method.â
This is the description of an actual error I was asked about. And a tricky one, too.
photo.save would complain that the url is missing until you called
photo.url = "http://example.com/photo.img"
That got it to save the Photo record without complaint, but the url column still was nil when the record got reloaded.
The culprit it turns out was this little typo:
class Photo attr_accessor :url end
where it should have been
attr_accessible :url
Easy to get wrong and easy to miss, this one actually overwrites the url method that ActiveRecord generates with a plain old accessor, but the validation still validates the method and its value properly. The value just doesnât end up in the attributes hash anymore and therefore doesnât get persisted.
The devil is in the details.











