Helper method to check validation errors
Rails 5 got a new feature that allows to get machine-friendly name of validation error.
But you can use it now with activemodel-errorsdetails gem.
More: https://cowbell-labs.com/2015-01-22-active-model-errors-details.html
Here's a simple helper method to check if given validation error exists on a record.
module CheckValidationDetails
  # Check if the given error exists on given attribute
  #
  # @param attribute [Symbol] model attribute
  # @param error [Symbol] machine-friendly error name
  # @return [Boolean] whether or not any given error exists
  def error?(attribute, error)
    errors.details.key?(attribute) && errors.details[attribute].any? { |err| err[:error] == error }
  end
end
Usage:
class User
  include CheckValidationDetails
end
user.new(name: nil, email: "not_taken@email.com")
user.save
user.error? :name, :blank  # == true
user.error? :email, :taken  # == falseWritten by Andrew Volozhanin
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
 #Ruby 
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#