Help us understand the problem. What is going on with this article?

【Rails】Enumerize Enum 個人まとめ

More than 1 year has passed since last update.

参考サイト

導入

gem 'enumerize'

pryで確認

values で確認

[3] pry(main)> User.user_authority_id
=> #<Enumerize::Attribute:0x00005583d8ea3b78
 @klass=
  User(id: integer, user_authority_id: integer, company_id: integer, name: string, email: string, password_digest: string, created_at: datetime, updated_at: datetime),
 @name=:user_authority_id,
 @value_hash={"1"=>"admin", "2"=>"consultant", "3"=>"user", "admin"=>"admin", "consultant"=>"consultant", "user"=>"user"},
 @values=["admin", "consultant", "user"]>
[4] pry(main)> User.user_authority_id.values
=> ["admin", "consultant", "user"]

options

[6] pry(main)> User.user_authority_id.options
=> [["Admin", "admin"], ["Consultant", "consultant"], ["User", "user"]]

下記のような形でvaluesをチェックできる

user.user_authority_id.admin?

外部キーと主キーにはEnumを設定しない

https://stackoverflow.com/questions/552116/should-i-use-an-enum-for-primary-and-foreign-keys

外部キー、主キーに関しては、定数定義でよいという結論

モデルから定数の呼び出し

constant.rb
UserAuthority::ADMIN
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away