我想要一个类通过多态关联来
belong_to
其他类。
将关联限制为特定类列表的最佳方法是什么?
我正在考虑使用像这样的自定义验证方法,但我不知道这是否真的是最好的主意:
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
我们将此验证 (Rails 5) 用于多态类型:
ALLOWED_TYPES = %w(Star Planet).freeze
validates :moonable_type, inclusion: { in: ALLOWED_TYPES }
不久前我实现了这个 gem SafePolymorphic。
仅使用
validates
的好处是它更简洁,更易于阅读,并且您可以获得一些帮助器,例如范围。
class Feature < ActiveRecord::Base
belongs_to :featureable, polymorphic: [Country, City, Store, Product]
end