LoginSignup
36
32

More than 5 years have passed since last update.

Rails 4.1から入った `enum` をi18n対応してみた。

Posted at

例えば、

app/models/user.rb
class User < ActiveRecord::Base
  enum sex: { male: 0, female: 1 }
end

となっていて、フォームでselect をi18n対応させたい。

config/locales/ja.yml
ja:
  activerecord:
    attributes:
      user:
        sex: 性別
          male: 男性
          female: 女性

と書きたいけど、YAMLの構文として誤りなので、これは出来ない。

よく考えてみると、これはattributesでは無いよなぁ、ということで、違う項目に出してみる。

config/locales/ja.yml
ja:
  activerecord:
    attributes:
      user:
        sex: 性別
    enum: # <= HERE!
      user:
        sex:
          male: 男性
          female: 女性

これなら、ハッシュで値ごとに表記名が出せる。

使い方としては、

app/views/users/_form.html.erb
<%= form_for(@user) do |f| %>
  <%= f.label :sex %>
  <%= f.select :sex, User.sexes.to_a.map { |s| [t("activerecord.enum.sex.#{s[0]}"), s[1]] } %>
<% end %>

みたいにすると、"男性”、"女性" が選択できるselect タグが生成できる。

でも、毎回、I18n.t を呼ばないといけないのは辛い。

36
32
2

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
36
32