Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

errors.add :base, "..." doesn't seem to prevent save #2837

Closed
barmstrong opened this Issue · 7 comments

3 participants

@barmstrong

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"
l.save
=> true

I'm trying this with a simple model:

class Log
  include Mongoid::Document
  include Mongoid::Timestamps

  field :text, type: String
end

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!

@barmstrong

Another example:

l = Log.new
l.errors.add :base, 'a'
l.errors.empty?
=> false
l.valid?
=> true
i.save!
=> true
@arthurnn
Owner

.errors.add will add an error message in ActiveModel, see. The model is still valid though, and it will save normally.

@durran
Owner

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:

https://github.com/rails/rails/blob/3-2-stable/activemodel/lib/active_model/validations.rb#L194

@durran durran closed this
@barmstrong

Does it work the same way in ActiveRecord? It seems like this violates least surprise.

Thanks for taking a look.

@durran
Owner

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.

@barmstrong

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)

@durran
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.