8
4

【Rails】enum 使う時はprefixを使いましょう

Last updated at Posted at 2023-12-24

はじめに

enumを使う時はprefixを使いましょう、という提案です。

なぜprefixを使うと良いのか

1.可読性が上がる2.拡張性が高くなるからです。

可読性が上がる

class Article < ApplicationRecord
  belongs_to :user
  enum :status, { unsaved: 10, draft: 20, published: 30 }, _prefix: status
end

_prefixがない場合も一見わかりやすいですが、個人的には_prefixを付与することで、モデルこのカラムこのステータスの状況が一目でわかりやすくなります。

_prefixがない場合
[3] pry(main)> article.published?
=> true
[4] pry(main)> article.draft?
=> false
[5] pry(main)> article.unsaved?
=> false
class Article < ApplicationRecord
  belongs_to :user
  enum :status, { unsaved: 10, draft: 20, published: 30 }, prefix: status
end
_prefixがある場合
[3] pry(main)> article.status_published?
=> true
[4] pry(main)> article.status_draft?
=> false
[5] pry(main)> article.status_unsaved?
=> false

拡張性が高くなる

例えば、同じようなステータスがある場合、重複によりエラーが出てしまいます。

class Conversation < ActiveRecord::Base
  enum status: { active: 0, archived: 10 }
  enum comments_status: { active: 0  inactive: 10 }
end
irb(main):004:0> c = Conversation.find(1)
ArgumentError (You tried to define an enum named "comments_status" on the model "Conversa

このような時も、あらかじめprefixを設定しておけば重複せずに管理することができます。

class Conversation < ActiveRecord::Base
  enum status: [:active, :archived], prefix: true
  enum comments_status: [:active, :inactive], prefix: true
end
[3] pry(main)> conversation.status_active? 
=> true

[5] pry(main)> conversation.comments_status_active? 
=> true
8
4
1

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
8
4