5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Administrate で enumフィールドを多言語化して表示する

Last updated at Posted at 2018-01-18

Administrateを使っていて、enumのプロパティをselectボックスで選ばせたかったので実装してみました。

実行環境

  • Rails 5
  • Administrate 0.8.1

方針

実装

ビューを追加する

$ rails generate administrate:field enum
app/views/fields/enum/_form.html.erb
<div class="field-unit__label">
  <%= f.label field.attribute %>
</div>
<div class="field-unit__field">
  <%= f.select(
    field.attribute,
    options_from_collection_for_select(
      field.selectable_options,
      :last,
      :first,
      field.data.presence,
    )
  ) %>
</div>
app/views/fields/enum/_index.html.erb
<%= field.data %>
app/views/fields/enum/_show.html.erb
<%= field.data %>

フィールドを追加する

lib/administrate/field/enum.rb
require "administrate/field/base"

module Administrate
  module Field
    class Enum < Field::Select
      def self.searchable?
        true
      end

      def selectable_options
        collection
      end

      private

      def collection
        if options.key?(:collection)
          options.fetch(:collection, [])
        else
          if resource_class.respond_to?(collection_method)
            resource_class.send(collection_method).map do |label, value|
              [I18n.t("enums.#{resource_class.name.underscore}.#{collection_method}.#{label}"), value]
            end
          else
            []
          end
        end
      end

      def resource_class
        @resource.class
      end

      def collection_method
        if options.key?(:collection_method)
          options.fetch(:collection_method)
        else
          @attribute.to_s.downcase.pluralize
        end
      end
    end
  end
end

実行例

プロフィールに性別を登録できるアプリを想定します。

app/models/profile.rb
class Profile < ApplicationRecord
  enum sex: %i(male female)
end
config/locales/ja.yml
ja:
  enums:
    sexes:
      male: 男性
      female: 女性
app/dashboards/profile_dashboard.rb
require "administrate/base_dashboard"

class ProfileDashboard < Administrate::BaseDashboard
  ATTRIBUTE_TYPES = {
    sex: Field::Enum,
  }.freeze

  COLLECTION_ATTRIBUTES = [
    sex: Field::Enum,
  ].freeze

  SHOW_PAGE_ATTRIBUTES = [
    sex: Field::Enum,
  ].freeze

  FORM_ATTRIBUTES = [
    sex: Field::Enum,
  ].freeze
end

実行結果

スクリーンショット 2018-01-18 9.54.07.png

参考

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?