adding errors to model in rails is not working
valid?
on a AR model clears the errors array, it does not check for whether you have errors in the errors array or not. As for save!
it runs validations which have nothing to do with the errors array. If you want to have errors in your model, you need to add validations to it.
If you read the code for valid?
this is what you'll see
ActiveRecord::Validations
def valid?(context = nil) context ||= (new_record? ? :create : :update) output = super(context) errors.empty? && outputend
The call of super(context)
is just a call to ActiveModel::Validations#valid?
which is the one responsible for clearing the errors array before running validations:
ActiveModel::Validations
def valid?(context = nil) current_context, self.validation_context = validation_context, context errors.clear run_validations!ensure self.validation_context = current_contextend
UPDATE
In order to add your custom errors, you have to do it on a validation method which adds it when the validation is checked. Anything before or after will just be cleared when you re-run validations.
Take a look at this resource http://guides.rubyonrails.org/active_record_validations.html#errors
The errors are added on a method that is called with validation.