Created
March 22, 2019 12:32
-
-
Save albb0920/61d0494b5446d1a090a76c7626e4cfd4 to your computer and use it in GitHub Desktop.
Use PostgreSQL enum as rails enum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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