3
2

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 専用のfield を作ったよ

Last updated at Posted at 2016-09-15

Rails の管理画面用gem の一つ、administrate を使い始めました
しかし、絶賛開発中という事があってかゆい所に手が届かない

今回はその一つ、enum をいい感じのSELECT で表現する にチャレンジします

enumissues はあがっていたのですが多言語化されてなかったのでその対応がメインになります!
https://github.com/thoughtbot/administrate/issues/420

まずはfieldgenerate

$ rails generate administrate:field enum_select

こんなファイル達を作ります

app/fields/enum_select_field.rb
app/views/fields/enum_select_field/_form.html.erb 
app/views/fields/enum_select_field/_index.html.erb
app/views/fields/enum_select_field/_show.html.erb

それぞれのファイルを以下のように修正

app/fields/enum_select_field.rb
require "administrate/field/base"

class EnumSelectField < Administrate::Field::Select
  def enum_options
    collection.map do |k, v|
       [I18n.t("enum_cd.#{@attribute}.#{k}"), k]
     end
  end
end
app/views/fields/enum_select_field/_form.html.erb
<div class="field-unit__label">
  <%= f.label field.attribute %>
</div>
<div class="field-unit__field">
  <%= f.select(
    field.attribute,
    field.enum_options
  ) %>
</div>
app/views/fields/enum_select_field/_index.html.erb
<%= t("enum_cd.#{field.attribute}.#{field.data}") %>
app/views/fields/enum_select_field/_show.html.erb
<%= t("enum_cd.#{field.attribute}.#{field.data}") %>

で仕上げに locale を修正

config/locales/ja.yml
ja:
  enum_cd:
    role:
      admin:   管理者
      member:   会員
      guest:   ゲスト

結果、こんな画面になります

スクリーンショット 2016-09-15 13.48.53.png

無事日本語になりました

3
2
3

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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?