rails: ActiveModel#Errors creates key in messages hash if there are any errors for that given key
If you want to access an error for an attribute with model.errors[:foo]
if there are any error on that attribute, it creates an entry on messages hash with this attribute name. So after try to access errors of an attribute if you want to get all error keys from the ActiveModel::Errors
instance it will return wrong keys. Lets look at the example;
post = Post.new
post.errors.keys # => []
post.errors[:foo] # => []
post.errors.keys # => [:foo]
I think this is intended behaviour but it’s weird and error prone. Is there any reason to create a key on messages hash for given attribute name if there are any errors on that attribute?
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 17 (13 by maintainers)
Exactly. But this behaviour is documented here. I know that it’s utterly weird to have side effect for a reader method but at least we have documentation about it.
One solution might be using a wrapper class around array or a class which is extended from array to store error messages which acts like falsy if it is empty.