JT's Blog

Do the right things and do the things right.

ActiveRecord Module - Enum

| Comments

ActiveRecord::Enum

目的

宣告文字用來說明欄位中數字的意義,以下介紹兩種方式,也可順便解釋使用enum 的好處

假設Conversation 有個status 的欄位,建立常數,使用Hash 表示 0、1,分別代表active、archived

w/o Enum

1
2
3
4
5
6
module Conversation
  STATUS = { 0 => "active", 1 => "archived" }
end

conversation = Conversation.last
STATUS[conversation.status] # active or archived

w/ Enum

官方建議:欄位必須建立預設值

1
2
3
4
5
6
class Conversation < ActiveRecord::Base
  enum status: {
    active: 0,
    archived: 1
  }
end

查看總共有哪些狀態(名字加複數)

1
2
Conversation.statuses
# { "active"=>0, "archived"=>1 }

查看目前狀態

1
2
3
conversation = Conversation.last
conversatino.active!
conversation.status # active

變更欄位狀態

1
2
3
conversation = Conversation.last
conversatino.archived!
conversatino.archived?  #true

查詢是否為此狀態

1
2
3
4
conversation = Conversation.last
conversatino.active!
conversatino.active?    #true
conversatino.archived?  #false

當作where 查詢條件

1
Conversation.where(status: [:active, :archived])

加入_prefix

1
2
3
4
5
6
class Conversation < ActiveRecord::Base
  enum comments_status: [:active, :inactive], _prefix: :comments
end

conversation.comments_inactive!
conversation.comments_active? # => false

加入_suffix

1
2
3
4
5
6
class Conversation < ActiveRecord::Base
  enum status: [:active, :archived], _suffix: true
end

conversation.active_status!
conversation.archived_status? # => false

轉成陣列 (options_for_select)

1
Conversation.statuses.invert.to_a # [[0, "active"], [1, "archived"]]

優點

  • database 仍儲存數字代碼,查詢速度較快
  • 程式部分仍可以使用文字方式開發,提高閱讀性

Reference

Comments