Rails多态关联:限制允许的类

时间:2016-11-18 16:14:18

标签: ruby-on-rails validation activerecord polymorphic-associations

我希望一个类通过多态关联属于其他类。

将关联限制为特定类列表的最佳方法是什么?

我正在考虑使用这样的自定义验证方法,但我不知道这是否真的是最好的想法:

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

1 个答案:

答案 0 :(得分:11)

我们将此验证(Rails 5)用于多态ID和类型:

ALLOWED_TYPES = %w(Star Planet).freeze

validates :moonable_id, presence: true, numericality: { only_integer: true }
validates :moonable_type, presence: true, inclusion: { in: ALLOWED_TYPES }