Localizing Enum Scopes and Queries
When querying data, it’s essential to return localized results dynamically.
Example: Fetching All Localized Statuses in Rails
Modify the model to return all translated enums:
class User < ApplicationRecord
enum :status, { active: 0, inactive: 1, banned: 2 }
def self.localized_statuses
statuses.keys.map { |key| [I18n.t("activerecord.attributes.user.statuses.#{key}"), key] }.to_h
end
end
Fetching Localized Statuses in Controllers
User.localized_statuses
#=> { "Active" => "active", "Inactive" => "inactive", "Banned" => "banned" }
This approach ensures consistency when using enums across the application.