Custom type support in ActiveRecord

138 views
Skip to first unread message

Mike Dillon

unread,
May 22, 2016, 6:25:42 PM5/22/16
to Ruby on Rails: Core
I'm interested in using Postgres's custom type support with Rails, particularly enumerated types. I see that this topic was previously brought up on this list here, but it did not seem to generate any discussion.

Would there be any interest in supporting Postgres custom enumerated types in ActiveRecord?

As a first pass, I would want to ability to run "CREATE TYPE foo AS ENUM(...)" statements in migrations and have them captured in schema.rb, as well as being able to use custom types alongside native types in my column definitions. I could eventually see it making sense to allow ActiveRecord "enum" declarations to defer to a native database enumeration if it exists, but the "enum" method doesn't seem to have been aligned with the recent upgrades to the type system through the "attribute" keyword and ActiveRecord::Type.

-md

Nicholas Firth-McCoy

unread,
May 23, 2016, 8:35:32 AM5/23/16
to Ruby on Rails: Core
I'm definitely interested in this.

If you just want to be able to create enums in an `ActiveRecord::Migration`, the SchemaPlus::Enums gem is worth a look.

I think the more interesting thing would to have `ActiveRecord::Enum`backed by Postgres, but this raises hard questions about cross-database compatibility. It's a bit of a can of worms!

There's also an interesting post here that talks about some of the issues with the current implementation. I believe some of these have been addressed by Rails 5.

Mike Dillon

unread,
May 25, 2016, 1:20:47 PM5/25/16
to Ruby on Rails: Core
Thanks for the tip about SchemaPlus::Enums, Nicholas. That definitely makes creating the enums nicer.

Unfortunately, I don't think that fixes the fact that a table that uses an enum as a column type can't be dumped into schema.rb. It ends up hitting this code that calls "valid_type?(type)" on the connection adapter: https://github.com/rails/rails/blob/2a71885a3f88562c57f81230d31518e5189c0dda/activerecord/lib/active_record/schema_dumper.rb#L145

Since the PostgreSQL adapter currently only considers native types to be "valid", tables using enums are not dumped: https://github.com/rails/rails/blob/c0d4aa2293db9d2a5c69a57920edcd4f43776e91/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L375-L377

I agree about the difficulties of having ActiveRecord::Enum use a native database enum, though I still think it would be nice. I'd settle for being able to do something with an "attribute" declaration instead and avoiding "enum", since I don't generally use the helper methods that "enum" generates.

-md
Reply all
Reply to author
Forward
0 new messages