Showing custom error message on validation fails.

Hi there,

I have run into a scenario that I can't find anywhere on the internet for some reason.

I have a custom validator like so.

def sector_count_within_bounds
if sectors.size > 5
self.errors[:Sectors] << "Too much" end end It correctly stops my object from saving when it should. But instead of showing the error messages on the form itself. It just raises a ActiveRecord::RecordInvalid error. Saying that the the validation failed and that the object is invalid. That's perfect, the validation is supposed to fail. But why isn't it returning to my object edit page and showing the error with the message I provided? Any help is appreciated

1 thought on “Showing custom error message on validation fails.”

  1. I think your first issue is with how your setting the key for the `errors` hash. Your code:

    def sector_count_within_bounds
    if sectors.size > 5
    self.errors[:Sectors] << "Too much" end end Needs to be: def sector_count_within_bounds if sectors.size > 5
    self.errors[:Sectors] = “Too much”
    end
    end

    This will set the value for the `:Sectors` key. I’ve not seen the `<<` to set a value, only for adding objects to arrays. I could be wrong, so feel free to ignore. In terms of displaying validation errors, there is a section on the rails guides that goes over this: http://guides.rubyonrails.org/v4.2/active_record_validations.html#displaying-validation-errors-in-views

    Reply

Leave a Comment