【发布时间】:2013-05-19 13:50:07
【问题描述】:
我有一个Category 模型,它可以有多个父类和子类。我使用包含parent_category 和child_category 属性的Hierarchy 模型对此进行了建模。
我可以使用
验证行是唯一的validates_uniqueness_of :parent_category_id, scope: :child_category_id
这(以及数据库中相应的唯一索引)注意没有代表相同父子关系的多行。
但是,我想防止有人将孩子的父母指定为孩子。例如。如果类别 A 是类别 B 的父类别,则将类别 A 指定为类别 B 的子类别会导致验证错误。
我能想到的唯一方法是在validate 方法中查询数据库。
def child_parent_messup
unless Hierarchy.where(child_category_id: parent_category_id, parent_category_id: child_category_id).blank?
errors[:base] << "This child is also a parent of the same class."
end
end
如何改进?
【问题讨论】:
标签: ruby-on-rails activerecord