【问题标题】:Rails 6 and active admin translate enum field in show and index pagesRails 6 和活动管理员在显示和索引页面中翻译枚举字段
【发布时间】:2020-11-08 19:30:21
【问题描述】:

Rails 6.0.3,activeadmin 2.8.1。 在模型中,我使用status 属性的枚举:

enum status: { draft: 0, created: 10, approved: 20, notified: 30, cancelled: 40 }

这是语言环境:

#config/locales/it.yml  
it:
  activerecord:
    models:
      fine:
        one: verbale
        other: verbali
    attributes:
      fine:
        statuses:
          draft: bozza
          created: creato
          approved: approvato
          notified: notificato
          cancelled: cancellato

在显示中的 Activeadmin 和索引页面中,罚款的状态没有被翻译。

http://localhost:3000/admin/fines/30

http://localhost:3000/admin/fines

在编辑页面中,状态选择框已翻译。编辑后显示页面,但未翻译枚举字段。

在 ActiveAdmin 中翻译枚举字段的最佳方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby activeadmin


    【解决方案1】:

    您可以使用装饰器来做到这一点。我尝试了draper gem,以下对我有用:

    # app/decorators/fine_decorator.rb
    
    class FineDecorator < Draper::Decorator
      delegate_all
    
      def status
        I18n.translate(super, scope: 'activerecord.attributes.fine.statuses')
      end
    end
    
    # app/admin/fines.rb
    
    ActiveAdmin.register Fine do
      decorate_with FineDecorator
      ...
    end
    

    如果你想有更通用的解决方案,你可以在基础应用装饰器中引入translate_attribute helper:

    # app/decorators/application_decorator.rb
    class ApplicationDecorator < Draper::Decorator
      def self.translate_attribute(attribute)
        define_method attribute do
          I18n.translate(
            super(),
            scope: [
              self.class.object_class.i18n_scope,
              :attributes,
              self.class.object_class.model_name.i18n_key,
              attribute.to_s.pluralize
            ]
          )
        end
      end
    end
    
    # app/decorators/fine_decorator.rb
    class FineDecorator < ApplicationDecorator
      translate_attribute :status
      translate_attribute :other_enum_field
    end
    

    这一切都可以在不使用 draper gem 的情况下实现,但它需要对装饰器类进行更多调整。

    【讨论】:

      猜你喜欢
      • 2013-12-28
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多