af83

Internationalizing database validation error messages in Ruby on Rails

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

require 'localization'

class ActiveRecord::Errors
  include Localization
  def add_on_blank(attributes, msg = @@default_error_messages[:blank])
    for attr in [attributes].flatten
      value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
      if value.blank?
        add(l(attr), msg)
      end
    end
  end

  def add(attribute, msg = @@default_error_messages[:invalid])
    @errors[l(attribute).to_s] = [] if @errors[attribute.to_s].nil?
    @errors[l(attribute).to_s] << msg
  end

end

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

blog comments powered by Disqus