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

rub*_*atz 3 validation activerecord ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

小智 12

我们使用此验证(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 }
Run Code Online (Sandbox Code Playgroud)

  • `validates :moonable_id,presence: true, numericity: { only_integer: true }`不是必需的,因为Rails已经检查了moonable记录是否存在。 (3认同)