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 using 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
We used this validation (Rails 5) for polymorphic type:
ALLOWED_TYPES = %w(Star Planet).freeze
validates :moonable_type, inclusion: { in: ALLOWED_TYPES }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With