我的阵列 category = ["Components for PC", "Soft", "OS"]
元素的数量可以有所不同 .
创建这些数组元素 Category
(来自 .csv 文件) . 在数组 category
中我需要 category[0]
是父类,而 category[1]
- 子类别,但是父类 category[2]
PC的组件=> Soft => OS
使用gem Ancestry
对于作品的两个元素这样的代码(虽然丑陋):
last = nil
csv.each do |row| # rows from the table
base = row[6].split('/')[0] # first element
parent_category = Category.create!(name: base) if Category.where(name: base).first.nil? # Create a base category
row[6].split('/').each do |category| #
if Category.where(name: category).first.nil? # if the category does not exist
last = Category.create!(name: parent_category) if last == nil # create base Category
# if the base exists, create her child
child = Category.create!(name: category, ancestry: Category.where(name: base).first.id) if last != nil
end
end
end
如何为任意数量的元素创建类别和子类别?
2 回答
对于每个csv行:
获取一系列类别名称
获取根类别名称并将其从数组中删除
按名称查找或创建根类别
然后,对于数组中剩余的每个类别名称:
按名称查找或创建子类别
将类别设置为下一个类别的父级
假设您在
categories
中获得了一系列类别 .