DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

1 2

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →