Enums and STI

Hi all,

I was thinking that someone might want the type column used with Single-Table Inheritance to be an Enum rather than a string. Is the counter argument that STI is responsible for the type column so it doesn’t matter?

If the inheritance_column did support enum, would the resulting code be repeating itself too much?

class User < ActiveRecord::Base

enum type: [:student, :teacher]

end

class Teacher < User

end

class Student < User

end

If there’s interest in this feature I would be happy to work on adding it.

Zac

Hi,

We have a project at my workplace which heavily relies on a custom in-house extension to ActiveRecord which does this

(but ofcourse in an uglier way). It’d be great if this was a builtin feature.

Hardcoding class names in table rows makes for tedious migrations whenever classes are renamed.

Good luck! :slight_smile:

Of course, if this was implemented then polymorphic association _type fields should also support Enums for consistency. I think this would be advantageous for the same reasons.

Hi,

We have a project at my workplace which heavily relies on a custom in-house extension to ActiveRecord which does this

(but ofcourse in an uglier way). It’d be great if this was a builtin feature.

Hardcoding class names in table rows makes for tedious migrations whenever classes are renamed.

I’m not sure that a call to update_all really counts as “tedious”:

StiBaseClass.where(type: ‘OldType’).update_all(type: ‘NewType’)

The biggest issue I see with using enums for this is that the possible values of an enum need to be listed someplace - reflecting on all the subclasses of StiBaseClass won’t work since the order isn’t stable under renaming.

This applies doubly to using enums in polymorphic association _type fields…

—Matt Jones

Hi @Zac_Moody, I am trying out the same thing cause of better and fast index support for integers as compared to strings.

In your example, if I just use enum like the following, everything works as expected.

enum type: [:Student, :Teacher]

Only issue is the auto generated methods and scopes provided by enum seems unusual cause of the capital letters, i.e

User.Student => for the list of students user.Student? => check if user is student.

Also, in a recent pull request: https://github.com/rails/rails/pull/39677 i saw this patch which fixes the capital letters issues, I am using this in my current project and everything works as expected out of box. Now, I wonder is this should be an ideal way of doing things of is it supposed to work at all :confused:

I have a requirement to list all the type values of STI. So I would like to maintain all the possible values of type alaskasworld

class ParentClass < ActiveRecord::Base
  def self.sti_types
    @sti_types ||= self.select(:type).distinct
  end
end