How to change human readable attributes depending on context in Rails?

Viewed 414

I know I can change the ActiveRecord names in a locale file, but is there a way to change them based on context rather than locale (while still leveraging locale files in the application)?

For a simple example (I have multiple circumstances where I need to accomplish this), if I have an address form in a wizard and a user selects a country, how could I change the label/error messages for a :zipcode attribute to display "Zipcode" to those who have selected United States, and "Postcode" to those who have selected United Kingdom?

Edit: What I mean is when a model attribute (country) changes, how to change the human readable attributes for (zipcode) based on the country selection. The users locale won't change (I am already making use of locale files for translations).

2 Answers

Best way to localize is to use I18n, check this post: https://guides.rubyonrails.org/i18n.html#setup-the-rails-application-for-internationalization

Basic I18n

First add locales in you application.rb controller

config.i18n.available_locales = ["en-GB",  "en-US"]
config.i18n.default_locale = "en-US"

Then create 2 files en-US.yml and en-GB.yml under config/locales

# en-GB.yml
en-Gb:
  zipcode: "PostCode"

# en-US.yml
en-US:
  zipcode: "ZipCode"

Then in your controller, you will need to set dictionary that will be used for translation. It is defined with the I18n.locale variable.

# example when locale is passing through params
before_action :set_locale

def set_locale
  I18n.locale = I18n.available_locales.include?(params[:locale]) ? params[:locale] : I18n.default_locale
end

And finaly in your views: <%= t('zipcode') %>

Or if you need in you ruby files:

I18n.t('zipcode')

Localize ActiveRecord Attributes

Same as above, you can create a active_record.en-US.yml under config/locales

# active_record.en-US.yml
en-US:
  activerecord:
    attributes:
      your_model_name:
        zipcode: 'ZipCode'

I accepted the other answer as I did end up using locale files as part of my solution.

What I did was a bit hacky, however:

  1. Set locale to {language}-{selected_country} before the necessary request
  2. Have specific overrides in those YAML files where necessary, fall back to standard attributes in base language file whenever possible.
  3. Make use of alias_attributes in the FormObject to minimise the need for the above hack.
Related