Search code examples
ruby-on-railsrubyactiverecordactivemodel

How to remove errors in after_validation in Rails


I want the ability to set some values on my model to null if they fail validation. I have my model set up something like this:

class MyModel < ApplicationRecord
  attr_accessor :should_set_fields_to_null_if_invalid

  NULL_IF_INVALID_FIELDS = [:address, :phone]

  after_validation :set_fields_to_null_if_invalid, if: :should_set_fields_to_null_if_invalid
  ...
  # custom validations for address and phone
  ...

  def set_fields_to_null_if_invalid
    NULL_IF_INVALID_FIELDS.each do |attribute|
      self[attribute] = nil if errors.key?(attribute)
      errors.delete(attribute)
    end
  end
end

Basically, I am removing the error if it exists and set the attribute to null but I'm getting the following errors:

     ActiveRecord::RecordInvalid:
       Validation failed: 
     # /Users/albertjankowski/.rvm/gems/ruby-3.0.3/gems/activerecord-6.1.7.3/lib/active_record/validations.rb:80:in `raise_validation_error'
     # /Users/albertjankowski/.rvm/gems/ruby-3.0.3/gems/activerecord-6.1.7.3/lib/active_record/validations.rb:53:in `save!'

Not sure why it is still failing without a validation message. Does anyone have a suggestion on implementing this?


Solution

  • I was able to get it working by instead of using after_validation, I just just used validation:

      after_validation :set_fields_to_null_if_invalid, if: :should_set_fields_to_null_if_invalid
    
    

    to

      validate :set_fields_to_null_if_invalid, if: :should_set_fields_to_null_if_invalid