enumまとめ
enumとは?
enumは列挙型は列挙型と呼ばれています。 列挙型は整数が割り当てられた文字を順番に出力していくことができます。
属性名、属性の値(ハッシュ)で指定することでenumを定義することができます。
enumのすごいところ
可読性が上がります。 例えば、statusカラムがあるとして、そのstatusカラムは以下の属性と値を持つと表現できます。
pending: 1000 # 審査待ち active: 2000 # 登録済み quit: 3000 # 退会後
以上の値を属性(pending, active, quit)からでも値(1000, 2000, 3000)を取得・更新することができます。 viewやcontroller、model内で属性名で表現できれば見やすさは高まります。
実例
コンソールで試します。
booleanで検証できる
> User.create(email: 'hoge@example.com', password: 'hogehoge') > profile = User.first.build_profile > profile.gender = 'man' > profile.man? => true > profile.woman? => false
破壊的メソッドで更新できる。
> profile.man! > profile.gender => "man"
ハッシュで取得できる
> Users::Profile.genders
属性名(キー)で設定できる。
> profile = Users::Profile.new(gender: :woman) > profile.woman? => true
値(バリュー)で設定できる。
> profile = Users::Profile.new(gender: Users::Profile.genders[:woman]) > profile.woman? => true
検索ができる
> profile = Users::Profile.new(gender: Users::Profile.genders[:woman]) > profile.user = User.first > profile.save > Users::Profile.woman => #<ActiveRecord::Relation [#<Users::Profile id: 2, user_id: 1, gender: "woman", created_at: "2018-07-28 15:33:28", updated_at: "2018-07-28 15:33:28">]>
属性名を日本語で取得することができる
enum_helpというgemを使うことで属性名を日本語にすることができます。
Gemfile
gem 'enum_help'
bundle install
ここでi18nを使います。i18nは ローカライズ(i18n)まとめ - 現場の開発 でまとめています。
config/locales/resource/users.ja.yml
ja: activerecord: models: user: ユーザー user_profile: プロフィール attributes: user: id: ユーザーID email: メールアドレス password: パスワード password_confirmation: パスワード(確認用) sign_in_count: ログイン回数 created_at: 登録日時 last_sign_in_at: 前回ログイン時刻 users/profile: user: ユーザー gender: 性別 enums: users: profile: gender: woman: 女性 man: 男性
コンソールで確認します。
> User.first.profile.gender_i18n => "男性"