Ruby on Rails is a great framework, but would you believe it .. it has no built-in support for localized error messages for model level validation.

The problem is that you can internationalize the error messages but not the field name. Which makes for some very weird behavior.

Here is a bit of code to solve the problem. You have to install localization_generator before.

How to have clean internationalized validation error messages in Ruby on Rails?

in the file app/contollers/application.rb

RUBY:
  1. require 'localization'
  2.  
  3. class ActiveRecord::Errors
  4.   include Localization
  5.   def add_on_blank(attributes, msg = @@default_error_messages[:blank])
  6.     for attr in [attributes].flatten
  7.       value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
  8.       if value.blank?
  9.         add(l(attr), msg)
  10.       end
  11.     end
  12.   end
  13.  
  14.   def add(attribute, msg = @@default_error_messages[:invalid])
  15.     @errors[l(attribute).to_s] = [] if @errors[attribute.to_s].nil?
  16.     @errors[l(attribute).to_s] <<msg
  17.   end
  18.  
  19. end

And that's it! the magic is done with the l() function from localization_generator

Leave a Reply

Creative Commons License
This work is licensed under a Creative Commons Attribution 2.0 License.