Automatically validate polymorphic belongs_to type column

Let’s imagine an app with several models, and a particular polymorphic association:

class Banana < ApplicationRecord
has_one :eater, as: :eatable
end

class Orange < ApplicationRecord
has_one :eater, as: :eatable
end

class Eater < ApplicationRecord
belongs_to :eatable, polymorphic: true
end

``

When exposed to this codebase, one would often perform a lookup on the code for usages of “as: :eatable” or “:as => :eatable” , etc, which can be a pain.

If you’re like me, you’d like to have some control over what exactly is “eatable”.

You can perhaps write something like this on “Eater” class:

validates :eatable_type, inclusion: {
in: %w[banana orange],
message: “you can’t eat a %{value}!”
}

What about having this validator automatically generated, with a simpler syntax? given the following code?

class Eater < ApplicationRecord
belongs_to :eatable, polymorphic: {
as: %w[banana orange]
message: “you can’t eat a %{value}!”
}
end

``

The “as” key can be something else,… can’t think of a better name now.

Also, we could perhaps allow a more compact version:

belongs_to :eatable, polymorphic: %w[banana orange]

``

WDYT?

I normally add an inclusion validation anyway, so encouraging developers to document the associations (for those that don’t normally add a validation) is a nice win that has the potential to save a lot of developer time when searching for or attempting to memorize the associations.

If I were to write Rails from scratch I’d disallow polymorphic: true, requiring that an array of classes be passed. Double wins like this (less mystery, DRY validations) are important for developer productivity IMO.

One note: %w[banana orange] isn’t valid in this case (the names need to be capitalized). I’m not sure if Rails accepts strings in cases like this; I’ve always used symbols e.g. for :class_name.