Skip to content

Instantly share code, notes, and snippets.

@joroshiba
Last active July 16, 2018 00:28
Show Gist options
  • Save joroshiba/66f337f93a6aa09af70ba1bdf6b88100 to your computer and use it in GitHub Desktop.
Save joroshiba/66f337f93a6aa09af70ba1bdf6b88100 to your computer and use it in GitHub Desktop.
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
@joroshiba
Copy link
Author

joroshiba commented Mar 8, 2018

Use this concern in your model and then call for instance postgres_enum_for :answers, type_name: :answers_type to make answers on your model behave like a enum with the enum value set in postgres db called answers_type.

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