Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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
like image 661
rubykatz Avatar asked Nov 18 '16 16:11

rubykatz


1 Answers

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

ALLOWED_TYPES = %w(Star Planet).freeze

validates :moonable_type, inclusion: { in: ALLOWED_TYPES }
like image 50
Mark Avatar answered Nov 19 '22 13:11

Mark