Search code examples
ruby-on-rails

Rails validation error message not showing


I am trying to add a custom error message for my model validation. Seen below:

validates :cost, numericality: { greater_than_or_equal_to: 0, message: :custom_error }

My en.yml looks like this:

en:
  activerecord:
    errors:
      messages:
        custom_error: "some error translation"

From everything I have read that should work. However, it only works in some cases. If I do the following it seems to work:

a = Item.new
a.valid? 
 # false
a.errors.messages
 # { :cost=>["some error translation"]}

In a rescue block I am catching that error and printing the message as seen here:

def subtract_costs
  item.cost: -10
  item.valid?
  puts "error: #{item.errors.messages}"
  # Above outputs "error: {:cost=>["some error translation"]}"
rescue StandardError => error
  puts error.message
  # Above outputs "Validation failed:"
end

That message is always coming out to Validation failed: . Does anyone know what could be causing the error message to be blank? I do not have any other locals or translations in my project.


Solution

  • After some digging I was able to find out that it wasn't related to custom error messages and instead the lack of errors.full_messages always being empty which affected every type of validation error (possibly other types of errors as well).

    Once I dug into that method I found that it was being overridden by the gem dynamic_form. I was able to remove the gem and that fixed the issue. I now see all error messages being returned properly.