【发布时间】:2016-11-18 16:14:18
【问题描述】:
我希望一个类通过多态关联属于其他类。
将关联限制为特定类列表的最佳方法是什么?
我正在考虑使用这样的自定义验证方法,但我不知道这是否真的是最好的主意:
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
【问题讨论】:
-
如果您希望该类在另一个类具有
has_many :features时抛出错误或某种错误,这是不可能的。
标签: ruby-on-rails validation activerecord polymorphic-associations