Skip to content

Instantly share code, notes, and snippets.

@albb0920
Created March 22, 2019 12:32
Show Gist options
  • Save albb0920/61d0494b5446d1a090a76c7626e4cfd4 to your computer and use it in GitHub Desktop.
Save albb0920/61d0494b5446d1a090a76c7626e4cfd4 to your computer and use it in GitHub Desktop.
Use PostgreSQL enum as rails enum
# Add the `native_enum` class method to your ApplicationRecord, like this,
# You can then use it in your model, and use postgres enum just like rails enum
#
# Eample:
# class Post < ApplicationRecord
# native_enum :status
# end
#
# Post.published.count => 0
class ApplicationRecord < ActiveRecord::Base
class << self
# Maps a pg enum column as rails enum
def native_enum(attribute)
column = column_for_attribute(attribute)
query = "SELECT enum_range(NULL::#{column.sql_type})"
values = PG::TextDecoder::Array.new.decode(connection.execute(query).values[0][0])
enum attribute.to_sym => Hash[values.zip(values)]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment