【问题标题】:ancestry: how to create categories and subcategories from the array?祖先:如何从数组中创建类别和子类别?
【发布时间】:2018-01-24 09:49:42
【问题描述】:

我的数组category = ["Components for PC", "Soft", "OS"]
元素的数量可以不同。
这些数组元素是由Category(来自 .csv 文件)创建的。 在数组category 中,我需要category[0] 是父类,category[1] - 子类,但父类category[2]

PC 组件 => 软件 => 操作系统

使用宝石祖先

对于这样的代码的两个元素的作品(虽然丑陋):

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

如何为任意数量的元素创建类别和子类别?

【问题讨论】:

    标签: ruby-on-rails arrays ruby ancestry


    【解决方案1】:

    对于每个 csv 行:

    1. 获取类别名称数组
    2. 获取根类别名称并将其从数组中删除
    3. 按名称查找或创建根类别

    然后,对于数组中剩余的每个类别名称:

    1. 按名称查找或创建子类别
    2. 将类别设置为下一个类别的父类别

    csv.each do |row| # rows from the table
      category_names = row[6].split('/')
    
      root_category_name = category_names.shift
    
      parent_category = Category.find_or_create_by!(name: root_category_name) # Finds or creates the root category
    
      category_names.each do |category_name|
        parent_category = Category.find_or_create_by!(name: category_name, parent: parent_category) # Finds or creates the child category, which is the root for next categories
      end
    end
    

    【讨论】:

      【解决方案2】:

      假设您在 categories 中获取类别数组。

      categories.each_with_index do |category, index|
        if index.zero? 
          parent = Category.create!(name: category)
        else
          Category.create!(name: category, ancestry: parent.id)
        end  
      end
      

      【讨论】:

        猜你喜欢
        • 2017-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-16
        • 1970-01-01
        • 1970-01-01
        • 2021-02-25
        • 1970-01-01
        相关资源
        最近更新 更多