DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

Constant Enum in Activerecord Rails

🤔 Situation & Motivation

Master data that is not so many records and not need to store into RDB because of the performance.
How we can store it in the code?

🦄 General solution

class Hoge
  module TYPE
    A = 1
    B = 2

    TYPE_NAMES = {
      A = 'alpha',
      B = 'beta'
    }

    def self.keys
      TYPE_NAMES.keys
    end

    def self.type_names
      TYPE_NAMES.value
    end
  end
end

👍 Enum directory solution

This is not the usual way, but it's ok for migration of the version.

Code template

app/enums/v2/status_enum.rb
app/enums/v2/position_enum.rb
module V2::StatusEnum
  GREAT = 1
  NOMAL = 2
  BAD = 3

  STATUS_NAMES = {
    GREAT => 'GREAT',
    NOMAL => 'NOMAL',
    BAD => 'BAD'
  }
end
module V2::PositionEnum
  BOSS = 1
  NOMAL = 2
  PLAYER = 3

  STATUS_NAMES = {
    BOSS => 'BOSS',
    NOMAL => 'NOMAL',
    PLAYER => 'PLAYER'
  }
end

Usage

user = User.where(status: V2::StatusEnum::GREAT)

<%= V2::StatusEnum::STATUS_NAMES[user.status] %>

🔗 Parent Note

Top comments (0)