DEV Community

Yaroslav Shmarov
Yaroslav Shmarov

Posted on • Originally published at blog.corsego.com on

Rails enums - different approaches

Enums are a Rails feature, not a Ruby feature.

  • good - we get validations for available options, can fire actions and scopes
  • bad - use integer to represent strings

Option 1

post.rb

  enum status: %i[draft reviewed published]

Enter fullscreen mode Exit fullscreen mode

migration:

  add_column :posts, :status, :integer, default: 0

Enter fullscreen mode Exit fullscreen mode

In this case, the order of enums is very important:

0 = draft 1 = reviewed 2 = published

If we add new values - add at the end of the array!

Option 2 - fix integer values to specific strings (better)

post.rb

  enum status: { draft: 2, reviewed: 1, published: 0 }

Enter fullscreen mode Exit fullscreen mode

Option 3 - map enum to strings (the best)

post.rb

  enum status: {
    draft: "draft",
    reviewed: "reviewed",
    published: "published"
  }

Enter fullscreen mode Exit fullscreen mode

migration:

  add_column :posts, :status, :string

Enter fullscreen mode Exit fullscreen mode

a few methods that can be called:

post.draft! # => true
post.draft? # => true
post.status # => "draft"

post.reviewed! # => true
post.draft? # => false
post.status # => "reviewed"
post.reviewed? # => true

Post.draft # => Collection of all Posts in draft status
Post.reviewed # => Collection of all Posts in reviewed status
Post.published # => Collection of all Posts in published status

Enter fullscreen mode Exit fullscreen mode

Other good posts on the topic:

Top comments (0)