Search code examples
ruby-on-railsrails-i18n

How do I add translations to an Active Model


I have this model:

class Coupon
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :id

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end
end

How can I add i18n translations to this model? Specifically:

  • How do I translate its model name?
  • How do I translate its attributes?
  • How do I provide custom translation for its submit button?

I am using SimpleForm.


Solution

  • In your config/locales folder, create an activerecord.nl.yml (e.g. for Dutch), then in that file put the active record translations as follows

    nl:
      activerecord: 
        models: 
          coupon: translation
          coupons: translation
    

    As for the labels and buttons, create a simple-form.nl.yml file, containing

    nl:
      buttons: &buttons
        submit: translation
        ...
    

    and

      labels: &labels
        name: translation
        ...
    

    at the end of that file, put

      simple_form:
        buttons:
          defaults:
            <<: *buttons
        labels:
          defaults:
            <<: *labels
    

    by splitting up the list of labels and buttons from the simple form section, you can also use them elsewhere in your views