Skip to content

Instantly share code, notes, and snippets.

@nsmmrs
Created April 22, 2023 20:28
Show Gist options
  • Save nsmmrs/ab758facd06054816f947013d97dddb2 to your computer and use it in GitHub Desktop.
Save nsmmrs/ab758facd06054816f947013d97dddb2 to your computer and use it in GitHub Desktop.
Rails "string_enum" Helper
class ApplicationRecord
def self.string_enum(column_name, values, **options)
enum column_name => values.map(&:to_s).index_by(&:itself), **options
end
end
@nsmmrs
Copy link
Author

nsmmrs commented Apr 22, 2023

This allows declaring an enum on a String column as easily (and clearly) as with an Integer column.

For example:

string_enum :upload_status, [:pending, :complete, :error], _prefix: :upload

(As opposed to:)

enum :upload_status, {
  pending: "pending", 
  complete: "complete", 
  error: "error",
}, _prefix: :upload

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment