You can clone with
HTTPS or Subversion.
I came across this but wasn't sure if it was a bug or the intended behavior.
l = Log.new
l.errors.add :base, "test"
I'm trying this with a simple model:
field :text, type: String
With an error added it should prevent the save right? I'm not sure if some other gem could be interfering? This is with mongoid 3.0.18. Thanks!
l = Log.new
l.errors.add :base, 'a'
.errors.add will add an error message in ActiveModel, see. The model is still valid though, and it will save normally.
This is because ActiveModel clears out all messages when valid? is called, so simply adding an error that is not part of a validator will never cause the model to be invalid:
Does it work the same way in ActiveRecord? It seems like this violates least surprise.
Thanks for taking a look.
It is the same way in AR. Actually IMO it's not violating least surprise as I wouldn't generally expect someone to add to the error messages outside of a validation.
Gotcha - didn't realize that. So if you do validate :some_method and inside def some_method do self.errors.add :base, '...', this will prevent the save since it is inside of a validation right? I guess I don't understand the difference since some_method doesn't have to return false or anything right. So it seems like all that is happening in there is the error gets added, but maybe I'm missing something. Thanks for the help! (off topic to Mongoid I know)
self.errors.add :base, '...'
That's exactly correct. The reason that validations don't return false is that they are actually implemented as callbacks in Active Model, and returning false from a callback halts the chain. It's pretty much so that if there are multiple errors with the validations, you see all of them when calling valid? and not just the first one it encounters.