Skip to content

Instantly share code, notes, and snippets.

@elspethsoup
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save elspethsoup/4fde92d3fbe4b2120585 to your computer and use it in GitHub Desktop.

Select an option

Save elspethsoup/4fde92d3fbe4b2120585 to your computer and use it in GitHub Desktop.
Make ActiveRecord 4.1 aware of native postgresql enums
# PostgreSQL enums support (adapted from https://coderwall.com/p/azi3ka)
# Should be fixed in Rails >= 4.2 (https://github.com/rails/rails/pull/13244)
# put this code in an initializer file
raise "Remove this patch!" if Rails.version >= "4.2.0"
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter
module OID
class Enum < Type
def type_cast(value)
value.to_s
end
end
end
def enum_types
@enum_types ||= begin
result = execute 'SELECT DISTINCT t.oid, t.typname FROM pg_type t JOIN pg_enum e ON t.oid = e.enumtypid', 'SCHEMA'
Hash[ result.map { |v| [ v['oid'], v['typname'] ] } ]
end
end
private
def initialize_type_map_with_enum_types_support(type_map)
initialize_type_map_without_enum_types_support(type_map)
# populate enum types
enum_types.reject { |_, name| OID.registered_type? name }.each do |oid, name|
type_map[oid.to_i] = OID::Enum.new
end
end
alias_method_chain :initialize_type_map, :enum_types_support
end
class PostgreSQLColumn
private
def simplified_type_with_enum_types(field_type)
case field_type
when *Base.connection.enum_types.values
field_type.to_sym
else
simplified_type_without_enum_types(field_type)
end
end
alias_method_chain :simplified_type, :enum_types
end
end
end
@elspethsoup
Copy link
Copy Markdown
Author

Updated version that works with rails 4.1

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