'Rails polymorphic association: Restrict allowed classes

I want a class to belong_to other classes through a polymorphic association.

What is the best way to restrict the association to a specific list of classes?

I am considering to use a custom validation method like so, but I don't know if this is really the best idea:

class Feature < ActiveRecord::Base

  belongs_to :featureable, polymorphic: true

  validate :featurable_is_of_allowed_class

  FEATURABLE_CLASSES = ["Country", "City", "Store", "Product"]

  def featurable_is_of_allowed_class
    if !FEATURABLE_CLASSES.include? featurable.class.name
      errors.add(:featurable, "class not allowed for association")
    end
  end

end


Solution 1:[1]

We used this validation (Rails 5) for polymorphic type:

ALLOWED_TYPES = %w(Star Planet).freeze

validates :moonable_type, presence: true, inclusion: { in: ALLOWED_TYPES }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1