115
77

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.

Rails5でenum定義したカラムの元の値を取得

Last updated at Posted at 2016-07-20

自分用メモです。
でも、きっと同じことにぶち当たる人はいるはずw

例えば・・・・

class User < ActiveRecord::Base
  enum role: { admin: 1, manage: 2, other: 3 }

  ...

こんな感じで定義されていたとして、

user = User.create(role: 1)

そのオブジェクトを作り、roleに割り当てた1という値を取りたい場合、
Rails4までは、

rails4
user[:role]
=> 1

だったのが、Rails5だと・・・、

rails5
user[:role]
=> 'admin'

な・・・なんだと・・・!?

Rails5でenumの元の値を取得する場合は、

rails5
user.role_before_type_cast
=> 1

または、

user.class.roles[user.role]

または、

User.roles[user.role]

とするらしい。(コメント頂きました!!)
うーーん、面倒だな・・。他のも方法ありそうなんだけどなぁ・・・
情報求む!!

115
77
5

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
115
77

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?