[英]How to validate uniqueness for siblings' name attribute?
I have Category
model with tree structure via ancestry
gem. 我有通过ancestry
树与树结构的Category
模型。 I'd like siblings to have unique names, for example: 我希望兄弟姐妹具有唯一的名称,例如:
Books:
Science
science (not valid)
But 但
Books:
Science
Children:
Science (valid)
How can I setup this validation? 如何设置此验证?
You can use Rails validate uniqueness with scope defined. 您可以使用Rails验证具有定义范围的唯一性 。
For example let's say you have a column called parent_id
then your validation would look like 例如,假设您有一列名为parent_id
的列,那么您的验证将类似于
validates :name, uniqueness: { scope: :parent_id }
You can write your own validator using ActiveRecord validate
to check the childrens of the parent record like: 您可以使用ActiveRecord validate
编写自己的验证器,以检查父记录的子代,例如:
class Category < ApplicationRecord
has_ancestry
validate :children_name_is_unique
def children_name_is_unique
return unless parent.try(:has_children?)
if Category.where(id: parent.child_ids, name: name).exists?
errors.add(:name, 'Duplicate children name')
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.