Last active
July 16, 2018 00:28
-
-
Save joroshiba/66f337f93a6aa09af70ba1bdf6b88100 to your computer and use it in GitHub Desktop.
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
module PostgresEnum | |
extend ActiveSupport::Concern | |
class_methods do | |
def postgres_enum_for(column, type_name:) | |
enums = ActiveRecord::Base.connection.exec_query <<-SQL | |
SELECT pg_enum.enumlabel AS enumlabel | |
FROM pg_type | |
JOIN pg_enum | |
ON pg_enum.enumtypid = pg_type.oid | |
WHERE pg_type.typname = '#{type_name}'; | |
SQL | |
hash = {} | |
enums.rows.flatten.each { |value| hash[value.to_sym] = value.to_s } | |
enum column => hash | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use this concern in your model and then call for instance
postgres_enum_for :answers, type_name: :answers_type
to makeanswers
on your model behave like a enum with the enum value set in postgres db calledanswers_type
.