DEV Community 👩‍💻👨‍💻

mixbo
mixbo

Posted on

How to elegantly use enum in rails

Alt Text

What is enum?

enum is data structure more simpley and readable also is a useful method can help us do more things than you thinks.

enum :status {open: 0, close: 1, unknow: -1}
Enter fullscreen mode Exit fullscreen mode

We can see status maybe open, close,unknow more readable for 0,1,-1 isn't it?

Use enum elegantly

On Rails use enum to defined select tag options is more simpley

# activity.rb
class Activity < ActiveRecordBase
  enum :status {open: 0, close: 1, unknow: -1}
end

# zh-CN.yml
zh-CN:
  active_records:
    enums:
     activity:
       open: 开启
       close: 关闭
       unknow: 未知

# en.yml
zh-CN:
  active_records:
    enums:
     activity:
       open: Opened
       close: Closed
       unknow: Unknown

# activities/_form.html.erb
<= f.select :status, Activity.status_options, {}, class:'form-control' %>
Enter fullscreen mode Exit fullscreen mode

All is done you just defined i18n for activity form add select tag to dom with options [open,close,unknow] The output

# The result 
<select class='form-control'>
  <option value='open'>开启</option>
  <option value='close'>关闭</option>
  <option value='unknow'>未知</option>
</select>
Enter fullscreen mode Exit fullscreen mode

It's too simple and elegantly

More useful API

# get enum value 0,1,-1, here status is open, close or unknow
Activity.statuses[status] #=> 0,1,-1

# opend?, close?, unknow?
activity = Activity.find(1)
activity.opend? #=> true | false
activity.close? #=> true | false

# open!
activity = Activity.find(1)
activity.open! #=> activity.update!(status: 0)
activity.close! #=> activity.update!(status: 1)

# with scopes
class Activity < ActiveRecordBase
  scope :open, ->{where(status: 0)}
  scope :close, ->{where(status: 1)}
  scope :unknow, ->{where(status: -1)}
end
Activity.open # where status = 0

# with not scope
class Activity < ActiveRecordBase
  scope :not_open, ->{where.not(status: 0)}
  scope :not_close, ->{where.not(status: 1)}
  scope :not_unknow, ->{where.not(status: -1)}
end
Activity.not_open # where status != 0
Enter fullscreen mode Exit fullscreen mode

Hope it can help you :)

Top comments (0)

🌖🌗🌘 Turn on dark mode in Settings