'Rails 6 Remove specific error - delete(:email)

I know I can use user.errors.delete(: email) to delete the email validation error, but if an email has multiple errors on it, I assume it would remove all the errors associated with email.

Do rails have a way to delete a specific error message? I would like to remove the :already_confirmed error only. Looking for something like: user.errors.delete( email: :already_confirmed)

=> #<ActiveModel::Errors:0x007feee7ab60ere8
 @base=
  #<User id: 123, email: "[email protected]", created_at: "2020-09-26 19:00:38", updated_at: "2020-09-26 19:01:27", first_name: nil, last_name: nil>,
 @details={:email=>[{:error=>:already_confirmed}]},
 @messages={:email=>["was already confirmed, please try signing in"]}>


Solution 1:[1]

There should really be a user.errors.remove() method in rails. However, this is how I did it, but I am still hoping for a cleaner way.

error_index = user.errors.details[:email].find_index{|i| i[:error] ==  :already_confirmed}
if error_index.present?
  user.errors.messages[:email].delete_at(error_index)
  user.errors.details[:email].delete_at(error_index)
end

Solution 2:[2]

ActiveModel doesn't support any interface to delete specific errors

But you can something like this:

errors.details[:email].reject! { |detail| detail >= { error: :taken } }
errors.messages[:email].delete(t("activerecord.errors.messages.taken"))

It's not very elegant. But I haven't found a more beautiful solution yet

First line contains Hash#>= method. It returns true if one hash is part of another. In the example above, the error hash (detail) will also have the :value key

Second line deletes element from array by content. You need to know error message. Use the right locale key value

Solution 3:[3]

Just came across this, you can do model.errors.clear

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lefty
Solution 2 mechnicov
Solution 3 Jess Brown