Rails の管理画面用gem の一つ、administrate を使い始めました
しかし、絶賛開発中という事があってかゆい所に手が届かない
今回はその一つ、enum をいい感じのSELECT で表現する にチャレンジします
enum
のissues
はあがっていたのですが多言語化されてなかったのでその対応がメインになります!
https://github.com/thoughtbot/administrate/issues/420
まずはfield
をgenerate
$ 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](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.amazonaws.com%2F0%2F11006%2F80329a44-5d17-b750-8a2b-c0f719253134.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=744d87e816b244ae61d11954c6149a43)
無事日本語になりました