Logan Rice Logan Rice - 3 months ago 9x
Ruby Question

Rails why is calling .valid? removing my error messages

Calling ActiveModel::Validations#valid? on my @item instance is removing my error messages. This is best shown by example.

[1] pry(#<ChangeObjectsController>)> @item.errors.add(:new_error, "new error has occurred")
=> ["new error has occurred"]
[2] pry(#<ChangeObjectsController>)> @item.errors.full_messages
=> ["Connection error has occurred", "New error new error has occurred"]
[3] pry(#<ChangeObjectsController>)> @item.valid?
=> true
[4] pry(#<ChangeObjectsController>)> @item.errors.full_messages
=> []

In my model class I am including the validation library (*note it does not inherit from ActiveRecord::Base):

include ActiveModel::Validations
extend ActiveModel::Naming

The error message is added in this way:
Can anyone provide clarity on this issue? For example, is this desired behavior and I am using it incorrectly?


This is normal behaviour. It would be inconsistent if valid? returned true but there were error messages. You can see in the rails source that valid? explicitly clears the error messages.

The normal way to add error messages is via a validation, either a built in one or a custom one.