验证以防止父亲将自己引用为儿童

时间:2014-08-06 14:16:21

标签: ruby-on-rails

我正在寻找一种解决方案,以防止“父母”将自己添加为“孩子”。

我的模型看起来像这样:

class Category < ActiveRecord::Base
  belongs_to :parent, :class_name => 'Category'
  has_many :children, :class_name => 'Category', :foreign_key => 'parent_id'
end

现在我找一个防止这样的事情的解决方案

parent = Category.create(name: "Parent")
Category.new(name: "Children", parent_id: parent.id).valid? # should be => false

1 个答案:

答案 0 :(得分:3)

您可以为此添加custom validation

这样的东西
class ParentValidator < ActiveModel::Validator
  def validate(record)
    if record.parent_id == record.id
      record.errors[:parent_id] << 'A record\'s parent cannot be the record itself'
    end
  end
end

class Category
  include ActiveModel::Validations
  validates_with ParentValidator
end

甚至更简单(如果它是一次性的东西)

class Category < ActiveRecord::Base
  validate :parent_not_self, on: :save

  def parent_not_self
    if parent_id == id
      errors.add(:parent_id, 'A record\'s parent cannot be the record itself')
    end
  end
end

当您尝试将记录本身指定为父记录

时,这两种情况都会生成验证错误