Using I18n to Translate Enum Labels
Rails provides I18n (Internationalization) to handle translations efficiently. We can define enum translations in locale files and use them dynamically in views and controllers.
Step 1: Define Translations in config/locales/en.yml
en:
activerecord:
attributes:
user:
statuses:
active: "Active"
inactive: "Inactive"
banned: "Banned"
For French translations, create config/locales/fr.yml
:
fr:
activerecord:
attributes:
user:
statuses:
active: "Actif"
inactive: "Inactif"
banned: "Banni"
Step 2: Fetch Translated Enum Labels in Rails
Now, modify the User
model to fetch translated enum labels:
class User < ApplicationRecord
enum :status, { active: 0, inactive: 1, banned: 2 }
def human_status
I18n.t("activerecord.attributes.user.statuses.#{status}")
end
end
Example: Getting Translated Status
I18n.locale = :fr
user = User.new(status: :active)
puts user.human_status # => "Actif"
I18n.locale = :en
puts user.human_status # => "Active"
By switching the locale dynamically, we automatically translate enum values without changing business logic.