我正在使用ancestry gem来创建子类别。之后,当我创建一个项目(项目模型)时,我使用以下组选择将项目与其所属的子类别相关联。选择的组将类别和子类别分组在一起。
<%= form.input :category, collection: @categories, as: :grouped_select, group_method: :children, label: false, include_blank: true %>
@categories = Category.where(ancestry: nil).order('name ASC')
此外,我还使用cocoon gem来创建多个子类别并将其与一个项目相关联。
现在,我想在模型内添加一个custom validate
方法,该方法将允许用户仅添加属于同一主要类别的子类别,否则将返回错误:
errors.add(:category, "you can only choose subcategories from he same category")
我有点迷于如何创建此validate
方法。也许首先我应该找到要添加的子类别:
subcategory = Category.find(category)
然后找到子类别所属的类别:
subcategory.root.name
但是之后,我现在知道该怎么办。
如何创建此validate
方法以允许用户仅添加属于同一主要类别的子类别,否则将返回错误?
谢谢你。非常感谢您对此提供的帮助。
[据我了解,分配给某项的所有类别都必须是同一类别的子类别。我认为它们必须是子类别。
在项目中写出custom validation method以验证所有子类别都有父级,并且所有子类别都相同。
class Item < ApplicationRecord
has_many categories
validate :categories_have_the_same_parent
private def categories_have_the_same_parent
if categories.any? { |cat| !cat.ancestry_id }
errors.add(
:categories,
:not_a_subcategory,
"All categories must be sub-categories"
)
end
if categories.each_cons(2).any? { |a,b| a.ancestry_id != b.ancestry_id }
errors.add(
:categories,
:different_ancestors,
"All categories must have the same parent."
}
end
end
end
关于此问题的诊断可以改进,以包括违规类别。
然后,在表单中,使用表单信息填充Item,并像往常一样检查Item的验证。
class ItemController < ApplicationController
def create
@item = Item.create!(...params...)
...creation succeeded...
rescue ActiveRecord::RecordInvalid => e
...creation failed...
end
end