Skip to content
grosser edited this page Sep 13, 2010 · 14 revisions

Translations on ActiveRecord models (on class-level)

    class Post < ActiveRecord::Base
      validates_presence_of :country_id, :message => _('Select one fool!')
    end

Someting like this did never work with GetText and can never work since at the point the class is loaded neither text_domain nor locale should be set
(no user has logged in yet). The only reason it will blow up now when using FastGettext
is that FastGettext will complain when no `text_domain/locale` is set whereas GetText gave no feedback and merrily returned the msgid.

There are 3 possible solutions I found:

  1. use validate do and add the message dynamic
  2. use Rails I18n framework, by adding
    activerecord:
      errors:
        models:
          post:
            presence: "Select one fool!"

to all config/locales/xxx.yml and remove the :message=>xxx part.
(my preferred solution since it is very simple and reduces logic)

3. Enable procs as custom messages with GeekQs monkey patch

    validates_length_of :archives, :minimum => 1, :message => proc {_('Dont do that!')}

(Note) Original GetText with gettext_rails works using N_()

These messages are then translated when form errors are displayed on “if translation-key exists, translate”-basis
Details


class Post < ActiveRecord::Base
validates_presence_of :country_id, :message => N_(‘Select one fool!’)
end
Clone this wiki locally