Categories
Computers

Simple localisation of Rails validation messages

Rails scaffolding can be good to get up running quickly but it can also be a problem. This is for instance true when it comes to localising the error messages presented by Rails (e.g. “X errors prohibited this <object> from being saved”). The issue is caused by two things:

  1. Rails includes English default message headers for the error box without being apparent how to change them.
  2. Each individual error is prefixed by the capitalised field name. Regardless of GUI language these will probably be in English.

The first of these issues can easily be solved by replacing the default <%= f.error_messages %> with something like:

<%= error_messages_for :item,
:header_message => "Försök igen",
:message => "Några av värdena du har angivit är inte giltiga:" %>

The second is a little harder but can be solved by realising that Rails calls the method human_attribute_name on the model object, passing the column name. While it would be possible to do a switch statement or a lookup array to translate the column name, I have found it easier to just return an empty string and to provide the exact error message as part of the validation instead.

validates_presence_of :name, "Namnet måste anges"


def self.human_attribute_name(attr)
return ""
end

css.php