Skip to content

Instantly share code, notes, and snippets.

@jcypret
Last active July 9, 2019 03:01
Show Gist options
  • Save jcypret/3b083fc1292d7f24cd26fa24af7788d2 to your computer and use it in GitHub Desktop.
Save jcypret/3b083fc1292d7f24cd26fa24af7788d2 to your computer and use it in GitHub Desktop.
Store ActiveRecord enums in database as strings rather than integers
# Store enums in database as strings rather than integers.
#
# Wraps `ActiveRecord::Enum`; just use `string_enum` instead of `enum`.
# https://api.rubyonrails.org/v4.2.11.1/classes/ActiveRecord/Enum.html
#
# Usage:
# extend StringEnum
# string_enum status: [:active, :archived]
#
module StringEnum
def string_enum(definitions)
definitions.each do |name, values|
enum name => values.each_with_object({}) { |value, enums| enums[value] = value.to_s }
# override attribute getter to return a symbol
define_method(name) { self[name]&.to_sym }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment